O'Reilly logo

Programming Elixir 1.2 by Dave Thomas

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

Streams—Lazy Enumerables

In Elixir, the Enum module is greedy. This means that when you pass it a collection, it potentially consumes all the contents of that collection. It also means the result will typically be another collection. Look at the following pipeline:

 [ 1, 2, 3, 4, 5 ]
 |> Enum.map(&(&1*&1))
 |> Enum.with_index
 |> Enum.map(​fn​ {value, index} -> value - index ​end​)
 |> IO.inspect ​#=> [1,3,7,13,21]

The first map function takes the original list and creates a new list of its squares. with_index takes this list and returns a list of tuples. The next map then subtracts the index from the value, generating a list that gets passed to IO.inspect.

So, this pipeline generates four lists on its way to outputting the ...

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