Eager vs Lazy
All the functions in the Enum
module are eager. Many functions expect an enumerable and return a list back:
iex> odd? = &(rem(&1, 2) != 0)
#Function<6.80484245/1 in :erl_eval.expr/5>
iex> Enum.filter(1..3, odd?)
[1, 3]
This means that when performing multiple operations with Enum
, each operation is going to generate an intermediate list until we reach the result:
iex> 1..100_000 |> Enum.map(&(&1 * 3)) |> Enum.filter(odd?) |> Enum.sum
7500000000
The example above has a pipeline of operations. We start with a range and then multiply each element in the range by 3. This first operation will now create and return a list with 100_000
items. Then we keep all odd elements from the list, generating a new list, now with 50_000
items, and then we sum all entries.