O'Reilly logo

Elixir Cookbook by Paulo A Pereira

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generating lazy (even infinite) sequences

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required