Skip to content

Instantly share code, notes, and snippets.

@mathewdgardner
Created March 14, 2017 21:23
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 mathewdgardner/b2bae3f7e086164bc344c0aaee2fe5b6 to your computer and use it in GitHub Desktop.
Save mathewdgardner/b2bae3f7e086164bc344c0aaee2fe5b6 to your computer and use it in GitHub Desktop.
Flatten a list with arbitrary depth in Elixir.
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
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