Hello,
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:
http://erlang.org/doc/efficiency_guide/listHandling.html#deep-and-flat-lists
BR, Borja
You can use Erlang functions in Elixir…
:list.append(list_of_list)
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)> :timer.tc(fn -> :lists.append(x) end)
{405, [:a, :a, ...]}
iex(34)> :timer.tc(fn -> Enum.concat(x) end)
{1039, [:a, :a, ...]}
If we test it more than 1 time:
iex(51)> Enum.sum(for _ <- 1..100, do: elem(:timer.tc(fn -> Enum.concat(x) end),0))
21491
iex(52)> Enum.sum(for _ <- 1..100, do: elem(:timer.tc(fn -> :lists.append(x) end),0))
5881
1 Like
NobbZ
5
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