Skip to content

Instantly share code, notes, and snippets.

@sasa1977
Created July 15, 2013 09:23
Show Gist options
  • Save sasa1977/5998616 to your computer and use it in GitHub Desktop.
Save sasa1977/5998616 to your computer and use it in GitHub Desktop.
list flattening
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