Last active
January 19, 2019 23:48
-
-
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
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 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