Created
July 15, 2013 09:23
-
-
Save sasa1977/5998616 to your computer and use it in GitHub Desktop.
list flattening
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 | |
def flatten(deep_list), do: collect_flattened([], deep_list) | |
defp collect_flattened(acc, []), do: acc | |
defp collect_flattened(acc, [h | t]) do | |
acc | |
|> collect_flattened(t) | |
|> flatten(h) | |
end | |
defp flatten(acc, []), do: acc | |
defp flatten(acc, [_|_] = list), do: collect_flattened(acc, list) | |
defp flatten(acc, element), do: [element | acc] | |
end | |
IO.inspect Flatten.flatten([]) | |
IO.inspect Flatten.flatten([1,2,3]) | |
IO.inspect Flatten.flatten([1,[[2,[[[3]]]]],[[[4], 5], 6], [], [[[]]]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment