I have a nested list [1, [2, [3, 4], 5], 6]. How do I flatten it, so that it becomes [1, 2, 3, 4, 5, 6]?
No need to re-invent the wheel, just use List.flatten/1
iex(1)> List.flatten([1, [2, [3, 4], 5], 6])
[1, 2, 3, 4, 5, 6]
Here's a good old recursive way (not tail-call optimised)
defmodule Test do
# degenerate case
def flatten([]), do: []
# list with more than 1 elt
def flatten([ head | tail ]) do
flatten(head) ++ flatten(tail)
end
# list with only one elt
def flatten(head), do: [ head ]
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With