← Back to lesson 21: Take only the data you need

Take only the data you need: full examples and further reading

The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.

Compare eager Enum work with a lazy Stream pipeline.

Build a lazy range pipeline and evaluate only its first three matching results.

Run this first

Run it once, change one input, and compare the new result.

Original full example
# 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.

Steps for the full example

  1. Read Stream.map/2: Add a lazy transformation.
  2. Read Stream.filter/2: Add a lazy filter.
  3. Read Enum.take/2: Consume only the requested number of values.

Original lesson notes

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.

Symbols and terms
Stream.map/2
Add a lazy transformation.
Stream.filter/2
Add a lazy filter.
Enum.take/2
Consume only the requested number of values.
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.

Original full exercise

Square a large range lazily and take the first two squares above 20.

Exercise starter
1..1_000
|> Stream.map(____)
|> Stream.filter(____)
|> Enum.take(2)

Return [25, 36].

Show hint

Square with &(&1 * &1) and keep values greater than 20.

Show original answer
Reference answer
1..1_000
|> Stream.map(&(&1 * &1))
|> Stream.filter(&(&1 > 20))
|> Enum.take(2)
What makes a Stream start producing values?

A consumer such as Enum.take/2 or Enum.to_list/1.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references