Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 of eager evaluation. What if we wish to work with data that doesn't fit in our available memory?

How to do it…

To work with enumerables and lazy evaluate them, we will follow these steps:

  1. Start an IEx session.

  2. Define an enumerable...