Elixir basics · Lesson 20 (open contents)
Take only the data you need
Compare eager Enum work with a lazy Stream pipeline.
Run this first
Run it once, change one input, and compare the new result.
# Describe a large pipeline, then ask for three results
result =
1..1_000_000
|> Stream.map(&(&1 * 2))
|> Stream.filter(&(rem(&1, 3) == 0))
|> Enum.take(3)
result- The pipeline returns
[6, 12, 18]without building a million-item result list.
Read from the first line down
- Read
Stream.map/2: Add a lazy transformation. - Read
Stream.filter/2: Add a lazy filter. - Read
Enum.take/2: Consume only the requested number of values.
Symbols are not secret signs
Stream.map/2Add a lazy transformation.
Stream.filter/2Add a lazy filter.
Enum.take/2Consume only the requested number of values.
Match each name to its meaning
eager
Enum functions compute their full result immediately.
lazy
Stream functions describe work and wait until a consumer asks for values.
terminal operation
A function such as Enum.take/2 asks a stream to produce results.
Why these forms are useful
Run the example first. Predict one result, then change one input and run it again.
Enum functions compute their full result immediately.
Stream functions describe work and wait until a consumer asks for values.
Close the answer and try
Square a large range lazily and take the first two squares above 20.
1..1_000
|> Stream.map(____)
|> Stream.filter(____)
|> Enum.take(2)Target result: Return [25, 36].
Stuck? Read one hint
Square with &(&1 * &1) and keep values greater than 20.
After you run it, see one answer
1..1_000
|> Stream.map(&(&1 * &1))
|> Stream.filter(&(&1 > 20))
|> Enum.take(2)Think about it: What makes a Stream start producing values?
A consumer such as Enum.take/2 or Enum.to_list/1.
Remember these three lines
- 1
Enum is eager.
- 2
Stream delays work.
- 3
Choose a bounded consumer for large or endless inputs.