Last active
November 2, 2021 19:02
-
-
Save veelenga/6057bdef7227bb4a23fcdd2394e0abec to your computer and use it in GitHub Desktop.
Flattening array in elixir
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
def flatten(list), do: flatten(list, []) |> Enum.reverse | |
def flatten([h | t], acc) when h == [], do: flatten(t, acc) | |
def flatten([h | t], acc) when is_list(h), do: flatten(t, flatten(h, acc)) | |
def flatten([h | t], acc), do: flatten(t, [h | acc]) | |
def flatten([], acc), do: acc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The above may overflow the stack.
See tail recursion version that I wrote: https://gist.github.com/heri16/e726ee7f335d2ca61bbbb016e6b884e1