Erlang equivalent to lists:append(ListOfLists)?


I have been looking for the equivalent of lists:append(ListOfLists) from Erlang in Elixir.

It terms of performance this is quite relevant as flatten is quite slower, see:

BR, Borja

You can use Erlang functions in Elixir…

1 Like

There is also Enum.concat which does basically the same thing.

Almost but not exactly the same:

iex(25)> x = for l <- 1..100, do: for b <- 1..100, do: :a
[:a, :a, ...]

iex(33)> -> :lists.append(x) end)
{405, [:a, :a, ...]}

iex(34)> -> Enum.concat(x) end)  
{1039, [:a, :a, ...]}

If we test it more than 1 time:

iex(51)> Enum.sum(for _ <- 1..100, do: elem( -> Enum.concat(x) end),0))
iex(52)> Enum.sum(for _ <- 1..100, do: elem( -> :lists.append(x) end),0))
1 Like

This is more or less expected. Enum.concat/1 is polymorphic, :lists.append/1 is specialised for lists.

Enum.concat/1 just calls Enum.reduce/3, which for lists shortcuts to Lists.foldl/3 IIRC:

:lists.append/1 though (I can’t find its source right now), might use :lists.foldr/3 as a matter of optimisation.

1 Like