JULIA / CHAPTER 06

Generators and deliberate materialization

Intermediate

Separate producing values from storing them.

By the end of this chapter

  • Build generators with filters
  • Reduce a sequence without collecting it first
  • Bound potentially infinite iterators

The idea

A generator describes values to compute as iteration proceeds. It can feed sum, any, or another consumer without first allocating a complete array of results. A comprehension with square brackets deliberately materializes an array instead. Both forms can express the same transformation, but their memory use and the timing of computation differ, especially when producing each item has a side effect.

Iterator composition also lets a finite consumer work with a potentially unbounded source. Bound that source with Iterators.take or an explicit stopping rule before a consumer that needs every item. Laziness does not imply caching or purity: a generator may calculate again when traversed again, and changing captured data can change later results. Make repeated traversal and ownership assumptions explicit.

Julia example
g = (n * n for n in 1:4 if iseven(n))
println(sum(g))
first_three = Iterators.take(Iterators.countfrom(1), 3)
println(join(collect(first_three), ","))
Result
20
1,2,3

The filtered generator contributes 4 and 16. take bounds the increasing source to three values before collection.

Try it yourself

Compute the sum of the first five positive multiples of three using an iterator pipeline.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which values contribute to this sum?
sum(n^2 for n in 1:4 if iseven(n))