In the Mapping and reducing enumerables recipe, we made use of the Enum
module. In this recipe, we will be using the Stream
module.
While Enum
functions are all eager, in Stream
, they are lazy.
Let's inspect the following code:
Enum.to_list(1..1000000) |> Enum.map(&(&1 * &1)) |> Enum.sum
This code is performing a sequence of operations using the Enum
module. All steps between the pipe operators (|>
) imply the calculation of the entire data structures and placing them in memory. A list with numbers from 1 to 1000000 is created, then a new list containing each of the previous elements multiplied by themselves is created, and finally, this resulting list is reduced by summing up all elements.
This is an example of eager evaluation. What if we wish to work with data that doesn't fit in our available memory?