Created
December 5, 2017 17:06
-
-
Save veverkap/25aae419e2436d4dc8b6b7793f345a0c to your computer and use it in GitHub Desktop.
This file contains 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 Flatten do | |
@moduledoc """ | |
Documentation for Flatten. | |
""" | |
@doc """ | |
Flattens an arbitrarily sized list | |
## Examples | |
iex> Flatten.flatten([]) | |
[] | |
iex> Flatten.flatten([[1,2,[3]],4]) | |
[1,2,3,4] | |
iex> Flatten.flatten([[[1],[2],[3]],4, 5, 6, 10, "apple"]) | |
[1,2,3,4, 5, 6, 10, "apple"] | |
# This test shows that this implementation is the same as the built-in List.flatten/1 method | |
iex> large_range = Enum.reduce(0..10000, [], fn(x, acc) -> acc ++ [x] end) | |
...> flattened = List.flatten(large_range) | |
...> flattened == Flatten.flatten(large_range) | |
true | |
""" | |
def flatten([]), do: [] | |
def flatten([head|tail]), do: flatten(head) ++ flatten(tail) | |
def flatten(item) when not is_list(item), do: [item] | |
end |
This file contains 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 FlattenTest do | |
use ExUnit.Case | |
doctest Flatten | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment