Conceptcore
Lazy sequence and stream
Also called lazy sequence, stream, lazy stream, lazy list, deferred sequence, lazy iterator, sequence (Kotlin), LazyList.
A lazy sequence produces its elements one at a time, only when a consumer asks for them. A pipeline of lazy stages does the work for one element at a time and can stop early.
- Applies to
- core-languages
Idea
A list holds all of its elements in memory. A lazy sequence holds a recipe for its elements and produces each one only when a consumer asks for it. When the stages of a pipeline are lazy, the consumer pulls one element through all the stages, then the next one, and the pipeline stops as soon as the consumer stops asking:
def numbers():
for n in range(1, 6):
print("produce", n)
yield n
squares = (n * n for n in numbers())
big = (s for s in squares if s > 5)
print("pipeline built")
print(next(big))
pipeline built
produce 1
produce 2
produce 3
9
Building the pipeline does no work. The call to next pulls numbers through the square stage and the filter stage until one passes, and 4 and 5 are never produced. The word stream has the same meaning in SICP and in the Java and Scala libraries; it is not the same thing as a byte stream for files and sockets.
How it works
A sequence with a delayed rest. SICP introduces streams as lists whose rest is not computed yet. "From an abstract point of view, a stream is simply a sequence", and delayed evaluation "enables us to represent very large (even infinite) sequences as streams."1 A stream cell holds the first element and a thunk for the rest of the stream. Taking the rest forces the thunk, which makes the next cell.
Demand drives the work. SICP calls this "demand-driven" programming, "whereby each stage in the stream process is activated only enough to satisfy the next stage." The program is written as if the streams existed all at once, while the computation "is performed incrementally".1 John Hughes describes the same idea for whole programs: a producer f "is started only when g tries to read some input, and runs only for long enough to deliver the output g is trying to read." He adds that this "allows termination conditions to be separated from loop bodies".2
Pull and push. Most lazy sequences use a pull protocol: the consumer calls a method such as next, and each stage calls next on the stage before it. Go uses a push protocol for its iterators. An iterator "is a function that passes successive elements of a sequence to a callback function, conventionally named yield. The function stops either when the sequence is finished or when yield returns false".3 In both protocols the consumer decides how much work is done.
Intermediate and terminal operations. A lazy library splits its operations into two groups. An intermediate operation, such as map or filter, returns another lazy sequence and does no work. A terminal operation, such as toList, sum or a for loop, pulls elements and starts the work. The Java documentation states: "Intermediate operations are always lazy."4 Kotlin uses the same split: if an operation returns another sequence, "it's called intermediate. Otherwise, the operation is terminal."5
Element by element, not stage by stage. An eager pipeline runs each stage over the whole collection and builds a full intermediate collection. Kotlin describes the difference: a Sequence "performs all the processing steps one-by-one for every single element", while an eager Iterable "completes each step for the whole collection and then proceeds to the next step."5
Stateless and stateful stages. A stage such as map, filter or take needs only the current element. A stage such as sorted or distinct needs to remember many elements. Kotlin notes that stateful operations "require a significant amount of state, usually proportional to the number of elements in a sequence."5 .NET calls a stateful stage eager inside a deferred query: "the OrderBy method has to sort the entire collection before it returns the first element."6
Two kinds of lazy sequence. An iterator or a generator is a cursor: it has a position, it moves forward, and it can be read one time. A memoized stream is a value: each cell, once computed, stays in memory, and any number of readers can walk it from the start. Scala's LazyList is the second kind. Its documentation states: "This class implements an immutable linked list", and the list "computes its elements only when they are needed."7 Haskell lists and SICP streams with memoized delay are also of this kind.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Absent | |
| C# | Standard library | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Standard library | |
| Rust | Standard library | |
| Kotlin | Standard library | Sequence<T>, generateSequence and the sequence builder give lazy sequences, and asSequence turns a collection into one; no example file because kotlinc is not installed on the machine that records the examples. |
| SQL | Does not apply | A query describes a result set, and the database decides how to produce it; a cursor that fetches rows on demand is the nearest idea. |
| Bash | Idiom | |
| PowerShell | Idiom | The pipeline passes objects one at a time, and Select-Object -First stops the earlier commands when it has enough objects; no example file because pwsh is not installed on the machine that records the examples. |
| HTML | Does not apply | HTML has no evaluation of expressions. |
| CSS | Does not apply | CSS has no evaluation of expressions. |
| Regular expressions | Does not apply | A regular expression has no sequences of values. |
| Language | Verdict | Lazy sequence | Kind |
|---|---|---|---|
| Python | native | generators, generator expressions, map, filter, itertools |
single-pass iterator |
| JavaScript | native | generator functions, iterator helpers | single-pass iterator |
| TypeScript | native | as JavaScript, typed Generator<T> and IterableIterator<T> |
single-pass iterator |
| Java | stdlib | java.util.stream.Stream |
single-use pipeline |
| Kotlin | stdlib | Sequence<T>, sequence { } |
re-runnable recipe |
| C# | stdlib | LINQ over IEnumerable<T>, yield return |
re-runnable recipe |
| Go | stdlib | iter.Seq[T] and iter.Seq2[K, V] |
push iterator |
| Rust | stdlib | the Iterator trait and its adapters |
single-pass iterator |
| C | absent | a struct with a next function |
hand-written iterator |
| C++ | stdlib | range views and adaptors | re-runnable view |
| Bash | idiom | a pipeline of processes | single-pass stream of lines |
| Haskell | native | every list | memoized stream |
Python. "An iterator is an object representing a stream of data", and an iterator can produce "an infinite stream of data."8 Generator functions and generator expressions make iterators, and itertools gives the lazy stages.
JavaScript. Iterator helpers, such as map, filter, take and drop on Iterator.prototype, are lazy. MDN notes that this style "only iterates the iterator once, without memorizing any intermediate values", and that "Iterator helper methods are necessary to work with infinite iterators".9
Java. A stream is lazy and "Consumable. The elements of a stream are only visited once during the life of a stream."4 A stream is also "Possibly unbounded", and "Short-circuiting operations such as limit(n) or findFirst() can allow computations on infinite streams to complete in finite time."4
C#. LINQ operators use deferred execution, which "means that the evaluation of an expression is delayed until its realized value is actually required."6 Enumerable.Take, for example, "is implemented by using deferred execution."10
Rust. "In Rust, iterators are lazy, meaning they have no effect until you call methods that consume the iterator to use it up."11
C++. Range adaptors "are applied to views lazily. Adaptors can be composed into pipelines, so that their actions take place as the view is iterated."12
Bash. The processes of a pipeline run at the same time and pass lines through pipes. A reader that exits early, such as head, stops the writer.
from itertools import count, islice
def square(n):
print("square", n)
return n * n
odd_squares = filter(lambda s: s % 2 == 1, map(square, count(1)))
print(list(islice(odd_squares, 2)))
square 1
square 2
square 3
[1, 9]
- Verdict: native.
map,filter,zip, generator expressions and the functions ofitertoolsreturn iterators that do no work until a consumer pulls.count(1)is infinite, andislicestops the pipeline after two odd squares. - An iterator is single-pass.
itertools.teegives several independent iterators over one source, and stores the elements that one reader has seen and another has not.
This code runs but gives a wrong answer on purpose.
squares = (n * n for n in range(4))
print(sum(squares))
print(sum(squares))
14
0
The second sum finds the generator used up and returns 0 with no error. Build a list if the values are needed twice.
#include <iostream>
#include <ranges>
#include <vector>
int square(int n) {
std::cout << "square " << n << '\n';
return n * n;
}
int main() {
auto odd_squares = std::views::iota(1)
| std::views::transform(square)
| std::views::filter([](int s) { return s % 2 == 1; })
| std::views::take(2);
std::vector<int> first;
for (int s : odd_squares) {
first.push_back(s);
}
std::cout << '[' << first[0] << ", " << first[1] << "]\n";
}
square 1
square 1
square 2
square 3
square 3
square 4
square 5
[1, 9]
- Verdict: stdlib.
views::iota(1)is infinite, and the adaptorstransform,filterandtakebuild a lazy view. The loop pulls the elements. - The trace shows two costs of views.
filtercallstransformto test an element, and the loop calls it again to read the element, sosquareruns twice for 1 and 3. After the second element, the loop advances the iterator before it compares it with the end, sofiltersearches on to 5. Keep the function oftransformcheap and free of side effects, or store its results.
import java.util.List;
import java.util.stream.Stream;
public class Main {
static int square(int n) {
System.out.println("square " + n);
return n * n;
}
public static void main(String[] args) {
List<Integer> oddSquares = Stream.iterate(1, n -> n + 1)
.map(Main::square)
.filter(s -> s % 2 == 1)
.limit(2)
.toList();
System.out.println(oddSquares);
Stream<Integer> once = Stream.of(1, 2, 3);
System.out.println(once.count());
try {
System.out.println(once.count());
} catch (IllegalStateException error) {
System.out.println("second use: " + error.getClass().getSimpleName());
}
}
}
square 1
square 2
square 3
[1, 9]
3
second use: IllegalStateException
- Verdict: stdlib.
Stream.iteratemakes an infinite stream.mapandfilterare intermediate and lazy,limitis a short-circuiting intermediate operation, andtoListis the terminal operation that starts the work. - A stream can be used only one time. The second terminal operation throws
IllegalStateException. ASupplier<Stream<T>>makes a fresh stream for each use.
#include <stdbool.h>
#include <stdio.h>
struct odd_squares {
int next_n;
};
static bool next_odd_square(struct odd_squares *it, int *out) {
for (;;) {
int n = it->next_n++;
printf("square %d\n", n);
int s = n * n;
if (s % 2 == 1) {
*out = s;
return true;
}
}
}
int main(void) {
struct odd_squares it = {.next_n = 1};
int first[2];
for (int i = 0; i < 2; i++) {
if (!next_odd_square(&it, &first[i])) {
return 1;
}
}
printf("[%d, %d]\n", first[0], first[1]);
return 0;
}
square 1
square 2
square 3
[1, 9]
- Verdict: absent. C has no iterator protocol and no closures. A lazy sequence is a struct that holds the state and a
nextfunction that computes one element per call. Each stage of a pipeline is code insidenext, or another struct that holds a pointer to the stage before it.
static int Square(int n)
{
Console.WriteLine($"square {n}");
return n * n;
}
var oddSquares = Enumerable.Range(1, int.MaxValue)
.Select(Square)
.Where(s => s % 2 == 1)
.Take(2);
Console.WriteLine("query built");
Console.WriteLine(string.Join(", ", oddSquares));
Console.WriteLine(oddSquares.Sum());
query built
square 1
square 2
square 3
1, 9
square 1
square 2
square 3
10
- Verdict: stdlib. LINQ operators such as
Select,WhereandTakeuse deferred execution: building the query does no work, and each enumeration runs it. - The query is a recipe, not a result.
Sumenumerates it a second time, soSquareruns again. CallToListonce when a result is needed more than one time.
function* naturals() {
for (let n = 1; ; n++) yield n;
}
const oddSquares = naturals()
.map((n) => {
console.log("square", n);
return n * n;
})
.filter((s) => s % 2 === 1);
console.log(oddSquares.take(2).toArray());
square 1
square 2
square 3
[ 1, 9 ]
- Verdict: native. A generator object is an iterator, and the iterator helpers
map,filter,take,dropandflatMapon it return lazy iterators.toArrayis a terminal operation that pulls the elements. - Array methods such as
Array.prototype.mapare eager: they build a full array at each step.
function* naturals(): Generator<number> {
for (let n = 1; ; n++) yield n;
}
function* map<T, U>(items: Iterable<T>, f: (item: T) => U): Generator<U> {
for (const item of items) yield f(item);
}
function* filter<T>(items: Iterable<T>, test: (item: T) => boolean): Generator<T> {
for (const item of items) if (test(item)) yield item;
}
function* take<T>(items: Iterable<T>, count: number): Generator<T> {
if (count <= 0) return;
for (const item of items) {
yield item;
if (--count === 0) return;
}
}
const squares = map(naturals(), (n) => {
console.log("square", n);
return n * n;
});
console.log([...take(filter(squares, (s) => s % 2 === 1), 2)]);
square 1
square 2
square 3
[ 1, 9 ]
- Verdict: native. The evaluation rules are those of JavaScript. Generic generator functions give typed lazy stages: each one is a
Generator<T>that pulls from the stage before it. takereturns right after the last element that it needs, so it does not pull one element too many from the stage before it.
package main
import (
"fmt"
"iter"
)
func naturals() iter.Seq[int] {
return func(yield func(int) bool) {
for n := 1; ; n++ {
if !yield(n) {
return
}
}
}
}
func mapSeq[T, U any](seq iter.Seq[T], f func(T) U) iter.Seq[U] {
return func(yield func(U) bool) {
for item := range seq {
if !yield(f(item)) {
return
}
}
}
}
func filterSeq[T any](seq iter.Seq[T], test func(T) bool) iter.Seq[T] {
return func(yield func(T) bool) {
for item := range seq {
if test(item) && !yield(item) {
return
}
}
}
}
func main() {
squares := mapSeq(naturals(), func(n int) int {
fmt.Println("square", n)
return n * n
})
odd := filterSeq(squares, func(s int) bool { return s%2 == 1 })
var first []int
for s := range odd {
first = append(first, s)
if len(first) == 2 {
break
}
}
fmt.Println(first)
}
square 1
square 2
square 3
[1 9]
- Verdict: stdlib. An
iter.Seq[T]is a push iterator: a function that callsyieldfor each element. Thebreakin thefor rangeloop makesyieldreturn false, and each stage then returns, so the infinite source stops. - The standard library has
iter.Seqsources, such asmaps.Keysandslices.Values, but nomaporfilterstages, so programs write small functions likemapSeq.
fn square(n: u64) -> u64 {
println!("square {n}");
n * n
}
fn main() {
let odd_squares: Vec<u64> = (1..).map(square).filter(|s| s % 2 == 1).take(2).collect();
println!("{odd_squares:?}");
let lazy = (1..=3).map(square);
println!("built, nothing printed yet");
let total: u64 = lazy.sum();
println!("{total}");
}
square 1
square 2
square 3
[1, 9]
built, nothing printed yet
square 1
square 2
square 3
14
- Verdict: stdlib. Iterator adapters such as
map,filter,take,skipandzipreturn lazy iterators.collect,sumand aforloop consume them. - The compiler warns about an adapter chain that is never consumed, with the note "iterators are lazy and do nothing unless consumed".
seq 1 1000000000 | awk '{ print $1 * $1 }' | awk '$1 % 2 == 1' | head -n 2
1
9
- Verdict: idiom. The processes of a pipeline run at the same time, and each one reads lines only as it needs them. When
headhas two lines, it exits. The next write of the secondawkthen fails withSIGPIPE, and the stop moves back toseq, so the billion numbers are never all produced. - The pipe has a buffer, so a producer can run some lines ahead of its consumer. The stages are lazy at the level of buffers, not of single elements.
Variations and related ideas
Generators. A generator function is the easiest way to write a lazy sequence in an eager language. It keeps its local variables between elements, so a loop with yield describes the whole sequence. See iterators.
Collection pipelines. A chain of map, filter and reduce is a collection pipeline. The chain can be eager, as with Kotlin lists, or lazy, as with Kotlin sequences and Java streams. The code looks the same, and the order of the work differs.
Infinite sequences. A lazy sequence can describe all natural numbers or all primes, because no code ever asks for all of them. See infinite data structures.
Lazy in the source, eager in a stage. A deferred query can still contain an eager stage. .NET separates the two ideas: an operator is deferred if it does no work until enumeration, and, once it runs, it is lazy if "a single element of the source collection is processed during each call to the iterator".6
Async and reactive streams. An asynchronous sequence, such as an async generator, also produces elements on demand, but the consumer waits for each element. Reactive streams push elements to subscribers as they arrive.
Pitfalls
A lazy sequence outlives its source. A lazy sequence reads its source when the consumer pulls, not when the code builds it. If the source is closed by then, the read fails:
This code runs but gives a wrong answer on purpose.
import io
def read_lines(text):
with io.StringIO(text) as source:
return (line.strip() for line in source)
lines = read_lines("a\nb\n")
try:
print(list(lines))
except ValueError as error:
print("error:", type(error).__name__)
error: ValueError
The with block closes the source when read_lines returns, before any line is read. Make the function a generator, so that the source stays open while the consumer reads:
import io
def read_lines(text):
with io.StringIO(text) as source:
for line in source:
yield line.strip()
print(list(read_lines("a\nb\n")))
['a', 'b']
Reading a single-pass sequence twice. A Python generator, a Java stream and a Rust iterator are used up by one pass. A second pass finds nothing, or fails.
Running a re-runnable recipe twice. A Kotlin sequence or a LINQ query runs its whole pipeline again for each terminal operation. If a stage is slow or has side effects, the work and the effects happen again. Store the result in a list when more than one consumer needs it.
Side effects at surprising times. The stages run interleaved, so a print in a map stage appears between the effects of other stages, and an effect in a stage that the consumer never reaches does not happen. Hughes wrote that the power of lazy evaluation depends on "the programmer giving up any direct control over the order in which the parts of a program are executed".2
A stateful stage on an infinite sequence. sorted, distinct over an unbounded range, count and reverse must see every element. On an infinite sequence they never return.
Cost
A lazy pipeline does not build intermediate collections, so it uses memory for one element per stage instead of one collection per stage. It can stop early, so a search does only the work needed to find the result. The price is overhead for each element: a call through each stage, and often a small object for the iterator state of each stage. Kotlin warns that "the lazy nature of sequences adds some overhead which may be significant when processing smaller collections or doing simpler computations."5 A memoized stream also keeps each computed cell while any code holds a reference to an earlier cell, so a reference to the head of a long stream can hold the whole stream in memory.
History
SICP traces lazy streams to Algol 60. Its footnote states that delayed evaluation "was inherent in Algol 60's call-by-name parameter-passing method. The use of this mechanism to implement streams was first described by Landin (1965). Delayed evaluation for streams was introduced into Lisp by Friedman and Wise (1976)."1 SICP made streams a main tool of its chapter 3, and Hughes's paper "Why Functional Programming Matters", in 1990, argued that lazy evaluation is "perhaps the most powerful tool for modularization in the functional programmer's repertoire."2 Eager languages took the idea in the form of generators, iterators and stream libraries, such as Python generators, Java streams, LINQ, Kotlin sequences, Rust iterators and C++ ranges.
References
- Structure and Interpretation of Computer Programs, H. Abelson and G. J. Sussman, second edition, MIT Press, 3.5 Streams; 3.5.1 Streams Are Delayed Lists; footnote 58
- Why Functional Programming Matters, J. Hughes, in Research Topics in Functional Programming, D. Turner, editor, Addison-Wesley, 1990, 4 Gluing Programs Together
- iter package, Go standard library, Iterators
- java.util.stream package summary, Java SE 25 API documentation, Streams differ from collections in several ways
- Sequences, Kotlin documentation, introduction; Sequence operations
- Deferred execution and lazy evaluation (LINQ to XML), .NET documentation, Deferred execution; Eager vs. lazy evaluation
- LazyList, Scala standard library API, class description
- Functional Programming HOWTO, Python 3.14 documentation, Iterators
- Iterator, MDN Web Docs, Iterator helper methods
- Enumerable.Take Method, .NET API documentation, Remarks
- Processing a Series of Items with Iterators, The Rust Programming Language, 13.2, introduction
- Ranges library, cppreference.com, introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag V6PDED Edit this page History Report an error Markdown