Created
March 14, 2017 21:23
-
-
Save mathewdgardner/b2bae3f7e086164bc344c0aaee2fe5b6 to your computer and use it in GitHub Desktop.
Flatten a list with arbitrary depth in Elixir.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Sample do | |
@moduledoc """ | |
Sample showcasing the power of Elixir recursion and flattening lists of arbitrary depth. | |
""" | |
@doc """ | |
Flatten lists with arbitrary depths. | |
## Examples | |
iex> Sample.flatten([:foo, [:bar]]) | |
[:foo, :bar] | |
""" | |
def flatten([]), do: [] | |
def flatten(list) when not is_list(list), do: [list] | |
def flatten([head | rest]), do: flatten(head) ++ flatten(rest) | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule SampleTest do | |
use ExUnit.Case | |
doctest Sample | |
test "should flatten empty list" do | |
assert [] = Sample.flatten([]) | |
end | |
test "should flatten list with single element" do | |
assert [:foo] = Sample.flatten([:foo]) | |
end | |
test "should flatten list with multiple elements" do | |
assert [:foo, :bar] = Sample.flatten([:foo, :bar]) | |
end | |
test "should flatten list with sub list" do | |
assert [:foo, :bar] = Sample.flatten([:foo, [:bar]]) | |
end | |
test "should flatten list with crazy depth" do | |
assert [:foo, :bar] = Sample.flatten([:foo, [[[[[:bar]]]]]]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment