Programming Search⌘K

Conceptadvanced

Infinite data structures

Also called infinite list, infinite stream, infinite sequence, codata, potentially infinite data, lazy infinite list.

An infinite data structure, such as the list of all primes, is defined by a rule and computed lazily. A program can use it because it only ever reads a finite part.

Applies to
core-languages

Idea

A program cannot store an infinite list, but it can store a rule that produces the elements of one. With lazy evaluation, the rule runs only for the elements that the program reads. So a program can define "all natural numbers" or "all powers of two" as a value, pass it around, and take as much of it as it needs:

from itertools import count, islice


def iterate(f, x):
    while True:
        yield x
        x = f(x)


powers_of_two = iterate(lambda x: 2 * x, 1)
print(list(islice(powers_of_two, 10)))

evens = (n for n in count(0) if n % 2 == 0)
print(next(evens), next(evens), next(evens))
Output
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
0 2 4

iterate has no end, and count(0) has no end. The program stops because islice and next ask for a finite number of elements. SICP describes the effect: "This is an infinitely long stream, but in any given time we can examine only a finite portion of it. Thus, our programs will never know that the entire infinite stream is not there."1

How it works

Potential infinity. An infinite structure is infinite only in what it can produce. John Hughes writes about an infinite list of approximations: "no more approximations will actually be computed than the rest of the program requires. The infinity is only potential".2 At any moment, memory holds a finite prefix and a suspended computation for the rest.

A head and a delayed tail. The classic form is a stream cell: a first element and a thunk for the rest. SICP defines the positive integers this way, with (cons-stream n (integers-starting-from (+ n 1))), and the rest of the stream is "a promise to produce the integers beginning with 2."1 Each force of the tail makes one more cell and one more promise.

Generators. An eager language usually expresses an infinite sequence as a loop that never ends, inside a generator or an iterator. The loop pauses after each element, so it runs only when the consumer asks. See lazy sequence and stream.

Corecursion. Recursion consumes a structure, and corecursion produces one. Wikipedia describes the difference: recursion handles "the topmost layer before descending into its inner parts", while corecursion "produces a data structure by first defining the topmost layer before defining its inner parts."3 A corecursive definition is safe when each step produces at least one element before it recurses. The Haskell Prelude defines iterate in this way, as iterate f x = x : iterate f (f x), and describes it as "an infinite list of repeated applications of f to x".4

Self-reference. A lazy structure can refer to itself. SICP defines the stream of ones as (define ones (cons-stream 1 ones)), and then defines the integers from the ones and from the integers: the first element is 1 and the rest "is the sum of ones and integers".1 The definition works "because, at any point, enough of the integers stream has been generated so that we can feed it back into the definition to produce the next integer."1 In Haskell, repeat x = xs where xs = x:xs builds one cell that points to itself, so an infinite list of the same value uses constant memory.4

Finite consumers. Only some operations make sense on an infinite structure. take n, takeWhile, find, first, indexing and a loop with break read a finite prefix and stop. length, sum, max, sort and reverse must see every element, so they never return. The Rust documentation warns that "methods on infinite iterators, even those for which a result can be determined mathematically in finite time, might not terminate."5

The prime sieve. The best-known example is the infinite stream of primes. SICP builds it as a sieve: take the first element of the stream as a prime, filter its multiples out of the rest, and sieve the result. "Thus, not only is the stream infinite, but the signal processor is also infinite, because the sieve contains a sieve within it."1 Melissa O'Neill pointed out that this famous program is not the sieve of Eratosthenes: the real sieve crosses off the multiples of each prime "starting from p2", and the stream program instead tests each number against every smaller prime. In her words, "this algorithm is not the Sieve of Eratosthenes!"6

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaStandard library
CAbsent
C#Standard library
JavaScriptNative
TypeScriptNative
GoStandard library
RustStandard library
KotlinStandard libraryGenerateSequence and the sequence builder make infinite sequences, and take, takeWhile and first read a finite prefix; no example file because kotlinc is not installed on the machine that records the examples.
SQLDoes not applyA table or a query result is finite; a recursive common table expression needs a limit or a condition to stop.
BashIdiom
PowerShellIdiomA script block with an endless loop can write objects to the pipeline, and Select-Object -First stops it; no example file because pwsh is not installed on the machine that records the examples.
HTMLDoes not applyHTML has no evaluation of expressions.
CSSDoes not applyCSS has no evaluation of expressions.
Regular expressionsDoes not applyA regular expression has no data structures.
Language Verdict Infinite source Finite consumer
Python stdlib itertools.count, cycle, repeat, a generator with while True islice, next, takewhile, break
JavaScript native a generator function with an endless loop iterator take, find, break
TypeScript native as JavaScript, Generator<T> as JavaScript
Java stdlib Stream.iterate, Stream.generate, IntStream.iterate limit, takeWhile, findFirst
Kotlin stdlib generateSequence, sequence { } take, takeWhile, first
C# stdlib an iterator method with yield return in an endless loop Take, TakeWhile, First
Go stdlib an iter.Seq function with an endless loop for range with break
Rust stdlib 0.., repeat, successors, from_fn, cycle take, take_while, find, nth
C absent a struct with a next function a loop with a bound
C++ stdlib views::iota(1), a coroutine generator views::take, views::take_while
Bash idiom yes, an endless while loop in a pipeline head
Haskell native [1..], iterate, repeat, cycle, recursive definitions take, takeWhile, !!

Python. itertools.count makes "an iterator that returns evenly spaced values beginning with start", and itertools.repeat "Runs indefinitely unless the times argument is specified."7

Java. Stream.iterate "Returns an infinite sequential ordered Stream" built from a seed and a function, and Stream.generate "Returns an infinite sequential unordered stream" from a Supplier.8

Kotlin. generateSequence builds a sequence from a function, and "The sequence generation stops when the provided function returns null", so a function that never returns null gives an infinite sequence.9

Rust. "Iterators do not have to be finite. As an example, an open-ended range is an infinite iterator".5

PythonGitHub
from itertools import accumulate, count, cycle, islice, repeat, takewhile
import operator


def primes():
    found = []
    for n in count(2):
        if all(n % p for p in takewhile(lambda p: p * p <= n, found)):
            found.append(n)
            yield n


powers_of_two = accumulate(repeat(2), operator.mul, initial=1)

print(list(islice(primes(), 10)))
print(list(islice(powers_of_two, 8)))
print(list(islice(cycle("abc"), 7)))
Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
[1, 2, 4, 8, 16, 32, 64, 128]
['a', 'b', 'c', 'a', 'b', 'c', 'a']
  • Verdict: stdlib. itertools.count, repeat and cycle are infinite iterators, and a generator with an endless loop, such as primes, is another. islice takes a finite prefix.
  • primes keeps the primes it has found and tests each number only against the primes up to its square root. The list grows with the number of primes read, so the generator is lazy but not constant in memory.
  • accumulate(repeat(2), operator.mul, initial=1) is an iterate: each element is the previous one times 2.
#include <iostream>
#include <ranges>

bool is_prime(int n) {
    for (int d = 2; d * d <= n; d++) {
        if (n % d == 0) {
            return false;
        }
    }
    return true;
}

int main() {
    auto primes = std::views::iota(2) | std::views::filter(is_prime);
    for (int p : primes | std::views::take(10)) {
        std::cout << p << ' ';
    }
    std::cout << '\n';

    auto powers = std::views::iota(0) | std::views::transform([](int n) { return 1 << n; });
    for (int x : powers | std::views::take(8)) {
        std::cout << x << ' ';
    }
    std::cout << '\n';

    auto small_squares = std::views::iota(1)
        | std::views::transform([](int n) { return n * n; })
        | std::views::take_while([](int s) { return s < 50; });
    for (int s : small_squares) {
        std::cout << s << ' ';
    }
    std::cout << '\n';
}
Output
2 3 5 7 11 13 17 19 23 29 
1 2 4 8 16 32 64 128 
1 4 9 16 25 36 49 
  • Verdict: stdlib. std::views::iota(2) with one argument is an unbounded range. The views filter, transform, take and take_while are lazy, so a loop over the result reads a finite prefix.
  • C++23 has no iterate view, so the powers come from iota(0) and a shift.
JavaGitHub
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Main {
    static boolean isPrime(int n) {
        for (int d = 2; d * d <= n; d++) {
            if (n % d == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        List<Integer> primes = Stream.iterate(2, n -> n + 1)
                .filter(Main::isPrime)
                .limit(10)
                .toList();
        System.out.println(primes);

        System.out.println(Stream.iterate(1, x -> 2 * x).limit(8).toList());

        int firstSquare = IntStream.iterate(1, n -> n + 1)
                .map(n -> n * n)
                .filter(s -> s > 50)
                .findFirst()
                .getAsInt();
        System.out.println("first square over 50: " + firstSquare);

        System.out.println(Stream.generate(() -> "ab").limit(3).toList());
    }
}
Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
[1, 2, 4, 8, 16, 32, 64, 128]
first square over 50: 64
[ab, ab, ab]
  • Verdict: stdlib. Stream.iterate(seed, f) and Stream.generate(supplier) make infinite streams. limit and findFirst are short-circuiting operations, so the pipeline stops after a finite number of elements.
  • Without limit, a terminal operation such as toList or count on these streams never returns.
#include <stdbool.h>
#include <stdio.h>

struct naturals {
    long next;
};

static long naturals_next(struct naturals *g) {
    return g->next++;
}

static bool is_prime(long n) {
    for (long d = 2; d * d <= n; d++) {
        if (n % d == 0) {
            return false;
        }
    }
    return true;
}

struct primes {
    struct naturals source;
};

static long primes_next(struct primes *g) {
    for (;;) {
        long n = naturals_next(&g->source);
        if (is_prime(n)) {
            return n;
        }
    }
}

int main(void) {
    struct primes g = {{2}};
    for (int i = 0; i < 10; i++) {
        printf("%ld ", primes_next(&g));
    }
    printf("\n");

    long x = 1;
    for (int i = 0; i < 8; i++) {
        printf("%ld ", x);
        x *= 2;
    }
    printf("\n");
    return 0;
}
Output
2 3 5 7 11 13 17 19 23 29 
1 2 4 8 16 32 64 128 
  • Verdict: absent. C has no generators. A struct holds the state of the infinite source, and a next function computes one element at each call. The caller's loop bound is the only limit.
  • primes wraps naturals: it pulls numbers until one is prime. A long overflows after enough calls, so the source is only infinite in principle.
using System;
using System.Collections.Generic;
using System.Linq;

static IEnumerable<long> NaturalsFrom(long n)
{
    while (true)
    {
        yield return n;
        n++;
    }
}

static IEnumerable<T> Iterate<T>(Func<T, T> f, T x)
{
    while (true)
    {
        yield return x;
        x = f(x);
    }
}

static bool IsPrime(long n)
{
    for (long d = 2; d * d <= n; d++)
    {
        if (n % d == 0)
        {
            return false;
        }
    }
    return true;
}

Console.WriteLine(string.Join(" ", NaturalsFrom(2).Where(IsPrime).Take(10)));
Console.WriteLine(string.Join(" ", Iterate(x => 2 * x, 1L).Take(8)));
Console.WriteLine(NaturalsFrom(1).Select(n => n * n).First(s => s > 50));
Output
2 3 5 7 11 13 17 19 23 29
1 2 4 8 16 32 64 128
64
  • Verdict: stdlib. An iterator method with yield return inside while (true) is an infinite sequence. LINQ's Where and Select are deferred, and Take and First stop the enumeration.
  • Count, Sum, ToList or OrderBy on NaturalsFrom(2) never return, and the compiler gives no warning.
JavaScriptGitHub
function* naturalsFrom(n) {
  for (;;) {
    yield n;
    n += 1;
  }
}

function* iterate(f, x) {
  for (;;) {
    yield x;
    x = f(x);
  }
}

function isPrime(n) {
  for (let d = 2; d * d <= n; d += 1) {
    if (n % d === 0) return false;
  }
  return true;
}

const primes = naturalsFrom(2).filter(isPrime);
console.log(primes.take(10).toArray().join(" "));
console.log(iterate((x) => 2 * x, 1).take(8).toArray().join(" "));

for (const n of naturalsFrom(1)) {
  if (n * n > 50) {
    console.log("first square over 50:", n * n);
    break;
  }
}
Output
2 3 5 7 11 13 17 19 23 29
1 2 4 8 16 32 64 128
first square over 50: 64
  • Verdict: native. A generator function with an endless loop is an infinite iterator. The iterator helpers filter and take are lazy, and toArray reads only the elements that take lets through.
  • A for...of loop with break also stops an infinite generator: the loop calls the return method of the generator, so the generator ends.
TypeScriptGitHub
function* naturalsFrom(n: number): Generator<number> {
  for (;;) {
    yield n;
    n += 1;
  }
}

function* iterate<T>(f: (x: T) => T, x: T): Generator<T> {
  for (;;) {
    yield x;
    x = f(x);
  }
}

function* filter<T>(items: Iterable<T>, test: (x: T) => boolean): Generator<T> {
  for (const item of items) {
    if (test(item)) yield item;
  }
}

function take<T>(items: Iterable<T>, count: number): T[] {
  const result: T[] = [];
  if (count <= 0) return result;
  for (const item of items) {
    result.push(item);
    if (result.length === count) break;
  }
  return result;
}

function isPrime(n: number): boolean {
  for (let d = 2; d * d <= n; d += 1) {
    if (n % d === 0) return false;
  }
  return true;
}

console.log(take(filter(naturalsFrom(2), isPrime), 10).join(" "));
console.log(take(iterate((x: number) => 2 * x, 1), 8).join(" "));
Output
2 3 5 7 11 13 17 19 23 29
1 2 4 8 16 32 64 128
  • Verdict: native. The generators are the same as in JavaScript, and the type Generator<number> records that they produce numbers. Nothing in the type says that a generator is infinite.
  • take checks the count before it asks for the next element. If it checked after, it would ask the infinite source for one element too many, which matters when an element is costly.
package main

import (
	"fmt"
	"iter"
)

func naturalsFrom(n int) iter.Seq[int] {
	return func(yield func(int) bool) {
		for ; ; n++ {
			if !yield(n) {
				return
			}
		}
	}
}

func iterate(f func(int) int, x int) iter.Seq[int] {
	return func(yield func(int) bool) {
		for ; ; x = f(x) {
			if !yield(x) {
				return
			}
		}
	}
}

func filter(seq iter.Seq[int], test func(int) bool) iter.Seq[int] {
	return func(yield func(int) bool) {
		for n := range seq {
			if test(n) && !yield(n) {
				return
			}
		}
	}
}

func take(seq iter.Seq[int], count int) []int {
	var result []int
	if count <= 0 {
		return result
	}
	for n := range seq {
		result = append(result, n)
		if len(result) == count {
			break
		}
	}
	return result
}

func isPrime(n int) bool {
	for d := 2; d*d <= n; d++ {
		if n%d == 0 {
			return false
		}
	}
	return true
}

func main() {
	fmt.Println(take(filter(naturalsFrom(2), isPrime), 10))
	fmt.Println(take(iterate(func(x int) int { return 2 * x }, 1), 8))
}
Output
[2 3 5 7 11 13 17 19 23 29]
[1 2 4 8 16 32 64 128]
  • Verdict: stdlib. An iter.Seq function with an endless loop is an infinite sequence. It must check the result of yield and return when it is false: after a break in the consumer, yield returns false, and the iter documentation states that yield panics if it is called again.
  • The standard library has no take or filter for iter.Seq, so the program writes them.
RustGitHub
fn is_prime(n: u64) -> bool {
    (2..).take_while(|d| d * d <= n).all(|d| n % d != 0)
}

fn main() {
    let primes: Vec<u64> = (2..).filter(|&n| is_prime(n)).take(10).collect();
    println!("{:?}", primes);

    let powers: Vec<u64> = std::iter::successors(Some(1u64), |x| Some(2 * x))
        .take(8)
        .collect();
    println!("{:?}", powers);

    let cycled: Vec<char> = "abc".chars().cycle().take(7).collect();
    println!("{:?}", cycled);

    let first_square = (1u64..).map(|n| n * n).find(|&s| s > 50);
    println!("first square over 50: {:?}", first_square);
}
Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
[1, 2, 4, 8, 16, 32, 64, 128]
['a', 'b', 'c', 'a', 'b', 'c', 'a']
first square over 50: Some(64)
  • Verdict: stdlib. The open range 2.. is an infinite iterator, and successors, repeat, from_fn and cycle make others. Adapters such as filter and map are lazy, and take, take_while and find stop.
  • is_prime also uses an infinite range, and take_while cuts it at the square root of n.
BashGitHub
naturals_from() {
  local n=$1
  while true; do
    echo "$n"
    n=$((n + 1))
  done
}

keep_primes() {
  local n d prime
  while read -r n; do
    prime=1
    for ((d = 2; d * d <= n; d++)); do
      if ((n % d == 0)); then
        prime=0
        break
      fi
    done
    if ((prime)); then
      echo "$n"
    fi
  done
}

naturals_from 2 | keep_primes | head -n 10 | paste -sd ' '
yes ab | head -n 3 | paste -sd ' '
Output
2 3 5 7 11 13 17 19 23 29
ab ab ab
  • Verdict: idiom. A pipeline is lazy by flow control: each command runs as its own process, and a write blocks when the pipe is full. naturals_from and yes never end on their own.
  • When head has its lines, it exits. The next write to its pipe fails with SIGPIPE, which stops keep_primes, and in turn naturals_from.

Cyclic structures. A finite cyclic structure, such as cycle [1, 2, 3] in Haskell, behaves like an infinite list but uses a fixed amount of memory. The Prelude defines cycle xs = xs' where xs' = xs ++ xs', and describes it as "the infinite repetition of the original list."4

Infinite trees. A game tree, the tree of all moves from a position, can be infinite. Hughes notes that if a game can "go on forever with neither side winning, its game tree is infinite." He builds such a tree lazily and prunes it to a fixed depth before evaluation, so the code that makes moves and the code that limits the search stay separate.2

Codata. Wikipedia calls the trees that recursion can consume data, or initial data types, because they are "not infinitely deep". It notes that corecursion "produces codata or final data types, which includes infinitely deep trees."3

Bounded but huge. A sequence of all 64-bit integers, or all lines of a log that grows, is finite, but a program treats it like an infinite one: it never builds it in full.

Pitfalls

A total operation on an infinite structure. len, sum, max, sorted or list on an infinite sequence never returns, and memory can grow until the program fails. Always put a limit, such as islice, take or limit, before such an operation.

A filter that never finds anything. filter on an infinite sequence is safe only if enough elements pass. A search for the first even prime greater than 2 runs forever.

Recursive stream code in an eager language. The SICP sieve, written with nested Python generators, adds two levels of nesting for each prime. The nesting soon passes the recursion limit:

This code runs but gives a wrong answer on purpose.

from itertools import count, islice


def sieve(numbers):
    p = next(numbers)
    yield p
    yield from sieve(n for n in numbers if n % p != 0)


try:
    print(len(list(islice(sieve(count(2)), 2000))))
except RecursionError as error:
    print("error:", type(error).__name__)
Output
error: RecursionError

The program is also slow. O'Neill describes it as a simple algorithm "known as trial division", and as even worse than the usual form of trial division, because it tests each number against all smaller primes, not only up to the square root. An incremental sieve keeps, for each prime found so far, the next multiple to cross off, and starts each prime at its square:

from itertools import count, islice


def primes():
    next_composite = {}
    for n in count(2):
        factor = next_composite.pop(n, None)
        if factor is None:
            next_composite[n * n] = n
            yield n
        else:
            m = n + factor
            while m in next_composite:
                m += factor
            next_composite[m] = factor


print(list(islice(primes(), 10)))
print(next(islice(primes(), 1999, None)))
Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
17389

Holding the head. With a memoized stream, every cell that the program has computed stays in memory while some variable refers to the first cell. A loop over a long prefix then uses memory in proportion to its length. Keep a reference only to the part that is still needed.

Side effects in the rule. A rule with side effects runs them when a consumer pulls, in an order that depends on the consumer. An infinite stream that reads input or prints output is hard to reason about.

Cost

An infinite structure costs only what the program reads. A generator uses constant memory for its state. A memoized stream uses memory for every cell that is computed and still referenced. Each element costs a call into the producer, and for a stream, a thunk allocation and a force. The algorithm inside the rule decides the rest: O'Neill shows that the stream sieve is "asymptotically worse than simple trial division", and that trial division in turn is worse than the true sieve.6

History

SICP traces the method to the 1960s: 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)."1 The same footnote states that Friedman and Wise brought delayed streams into Lisp in 1976. O'Neill notes that the sieve "has been cited in introductions to lazy functional programming for more than thirty years (Turner, 1975)", and her paper on the true lazy sieve appeared in the Journal of Functional Programming.6 Hughes used infinite lists of approximations and infinite game trees in "Why Functional Programming Matters" to show how laziness separates the producer of values from the code that decides when to stop.2 In Haskell, iterate, repeat and cycle are part of the standard Prelude.4

References

  1. Structure and Interpretation of Computer Programs, H. Abelson and G. J. Sussman, second edition, MIT Press, 3.5.2 Infinite Streams; Defining streams implicitly; footnotes 58 and 60
  2. Why Functional Programming Matters, J. Hughes, in Research Topics in Functional Programming, D. Turner, editor, Addison-Wesley, 1990, 4.1 Newton-Raphson Square Roots; 5 An Example from Artificial Intelligence
  3. Corecursion, Wikipedia, introduction
  4. Haskell 2010 Language Report, Standard Prelude, 9.1 PreludeList (iterate, repeat, cycle)
  5. Module std::iter, Rust standard library, Infinity
  6. The Genuine Sieve of Eratosthenes, M. E. O'Neill, Journal of Functional Programming, Abstract; 1 Introduction; 2 What the Sieve Is and Is Not
  7. itertools, Python 3.14 documentation, itertools.count; itertools.repeat
  8. Interface Stream, Java SE 25 API documentation, iterate; generate
  9. Sequences, Kotlin documentation, Construct, From a function

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/KEXF6B/text.yaml