Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I flatten a nested list in Elixir?

Tags:

elixir

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]?

like image 625
Ilya Suzdalnitski Avatar asked Mar 25 '26 07:03

Ilya Suzdalnitski


2 Answers

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]
like image 52
Adam Millerchip Avatar answered Mar 28 '26 03:03

Adam Millerchip


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
like image 20
MoVod Avatar answered Mar 28 '26 02:03

MoVod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!