Skip to content

Instantly share code, notes, and snippets.

@redrabbit
Created July 26, 2017 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redrabbit/85d400e88b01b6f8d0e3cb30b85b878f to your computer and use it in GitHub Desktop.
Save redrabbit/85d400e88b01b6f8d0e3cb30b85b878f to your computer and use it in GitHub Desktop.
Lazy path iterator in Elixir
defmodule RecursivePathIterator do
@moduledoc """
This module provides a simple interface for iterating over filesystem directories.
"""
@doc """
Walks the given `path` recursively.
"""
@spec walk(Path.t) :: Enumerable.t
def walk(path) do
case File.ls(path) do
{:ok, files} ->
files
|> Stream.map(&Path.join(path, &1))
|> Stream.map(&iterate/1)
|> Stream.concat()
{:error, _reason} ->
[]
end
end
#
# Helpers
#
defp iterate(path) do
if File.dir?(path),
do: walk(path),
else: [path]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment