Skip to content

Instantly share code, notes, and snippets.

@jordi-chacon
Last active January 19, 2019 23:48
Show Gist options
  • Save jordi-chacon/abde1b645ecb3fc6b5a70f6da422b12b to your computer and use it in GitHub Desktop.
Save jordi-chacon/abde1b645ecb3fc6b5a70f6da422b12b to your computer and use it in GitHub Desktop.
Elixir function that flattens an array of integers without using List.flatten
defmodule M do
def flatten(l) do
flatten(l, [])
|> Enum.reverse
end
def flatten([], acc) do
acc
end
def flatten([head | tail], acc) when is_integer(head) do
flatten(tail, [head | acc])
end
def flatten([head | tail], acc) when is_list(head) do
flatten(tail, flatten(head, acc))
end
end
# tests
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 20] =
M.flatten([1, 2, 3, [4], 5, [6, 7], [[8, [9, 10], [11, [12], [[13, [14]]]]]], 20])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment