ZetCode

Scheme streams and lazy evaluation

last modified November 25, 2026 Guile 3.0

Scheme evaluates the arguments of a procedure before it calls the procedure. This is eager evaluation. Lazy evaluation postpones a computation until its value is needed, and skips it if the value is never needed. Scheme supports it with promises, which delay creates and force evaluates. With promises, a list can have a tail that is computed on demand: a stream. Streams can be infinite, because only the elements that a program looks at are ever computed. The examples are run with GNU Guile 3.0.7.

Promises

delay is a special form. It does not evaluate its expression but returns a promise to evaluate it later. force evaluates the expression of a promise and returns its value.

promises.scm
(define answer
  (delay (begin
           (display "computing...")
           (newline)
           (* 6 7))))

(display "before force")
(newline)
(display (force answer))
(newline)
(display (force answer))
(newline)
(display (promise? answer))
(newline)

Defining answer prints nothing; the message appears only when the promise is forced. The second force returns 42 without computing it again: a promise remembers its value. This is called memoization, and it makes streams efficient, because every element is computed at most once. promise? tests for a promise. In Guile, force accepts only promises; a plain value such as 5 is an error.

$ guile promises.scm
before force
computing...
42
42
#t

Computing only when needed

A promise can be passed to a procedure that decides whether the value is needed at all. This avoids computations that are expensive, or that would fail, in the cases where their result is not used.

needed.scm
(define (slow-default name)
  (display "building default for ")
  (display name)
  (newline)
  (string-append name "-default"))

(define (lookup key alist default)
  (let ((entry (assq key alist)))
    (if entry
        (cdr entry)
        (force default))))

(define settings '((theme . "dark") (lang . "sk")))

(display (lookup 'theme settings (delay (slow-default "theme"))))
(newline)
(display (lookup 'font settings (delay (slow-default "font"))))
(newline)

lookup takes the default value as a promise and forces it only when the key is missing. For theme, the key is found and slow-default never runs. For font, the default is built. An ordinary argument would be computed before the call in both cases.

$ guile needed.scm
dark
building default for font
font-default

Building a stream

A stream is a pair whose car is the first element and whose cdr is a promise of the rest of the stream. Since delay is a special form, a procedure cannot create such a pair; a macro, as in the macros article, can.

integers.scm
(define-syntax cons-stream
  (syntax-rules ()
    ((_ a b) (cons a (delay b)))))

(define (stream-car s) (car s))
(define (stream-cdr s) (force (cdr s)))

(define (integers-from n)
  (cons-stream n (integers-from (+ n 1))))

(define (stream-head s n)
  (cond ((= n 0) '())
        ((= n 1) (list (stream-car s)))
        (else (cons (stream-car s) (stream-head (stream-cdr s) (- n 1))))))

(define naturals (integers-from 0))

(display (stream-car naturals))
(newline)
(display (stream-car (stream-cdr (stream-cdr naturals))))
(newline)
(display (stream-head naturals 10))
(newline)
(display (stream-head (integers-from 100) 3))
(newline)

cons-stream delays its second argument. stream-cdr forces the promise to get the rest of the stream. integers-from calls itself without a base case, which would never end with cons; with cons-stream, each call returns at once with the next call waiting in a promise. naturals is the infinite stream of the natural numbers, and stream-head collects its first elements into a list. The (= n 1) clause stops before the tail is forced, so stream-head computes exactly the elements it returns.

$ guile integers.scm
0
2
(0 1 2 3 4 5 6 7 8 9)
(100 101 102)

Mapping and filtering streams

Streams have their own versions of map and filter, which produce new streams lazily. The basic procedures are now collected in a module, as described in the modules article.

streams.scm
(define-module (streams)
  #:export (cons-stream stream-car stream-cdr integers-from
            stream-head stream-ref stream-map stream-filter))

(define-syntax cons-stream
  (syntax-rules ()
    ((_ a b) (cons a (delay b)))))

(define (stream-car s) (car s))
(define (stream-cdr s) (force (cdr s)))

(define (integers-from n)
  (cons-stream n (integers-from (+ n 1))))

(define (stream-head s n)
  (cond ((= n 0) '())
        ((= n 1) (list (stream-car s)))
        (else (cons (stream-car s) (stream-head (stream-cdr s) (- n 1))))))

(define (stream-ref s n)
  (if (= n 0)
      (stream-car s)
      (stream-ref (stream-cdr s) (- n 1))))

(define (stream-map f s . rest)
  (let ((streams (cons s rest)))
    (cons-stream (apply f (map stream-car streams))
                 (apply stream-map f (map stream-cdr streams)))))

(define (stream-filter keep? s)
  (if (keep? (stream-car s))
      (cons-stream (stream-car s) (stream-filter keep? (stream-cdr s)))
      (stream-filter keep? (stream-cdr s))))

stream-ref returns the element at an index. stream-map applies a procedure to the first elements of one or more streams and delays the mapping of the rest. stream-filter skips elements until it finds one to keep, then delays the filtering of the rest. On an infinite stream with no element to keep, it would search forever.

squares.scm
(use-modules (streams))

(define (square-noisy n)
  (display "[square ")
  (display n)
  (display "] ")
  (* n n))

(define squares (stream-map square-noisy (integers-from 1)))
(newline)

(define odd-squares (stream-filter odd? squares))

(display (stream-head odd-squares 3))
(newline)
(display (stream-head odd-squares 4))
(newline)
(display (stream-ref (stream-map + squares (integers-from 1000)) 2))
(newline)

square-noisy reports every square it computes. Creating squares computes only the first one. Taking three odd squares computes the squares up to 25 and no further. Taking four computes only the squares of 6 and 7, because the earlier elements are memoized. The last expression maps + over two streams; the element at index 2 is 9 + 1002. The program runs with -L ., so Guile finds the module in the current directory.

$ guile -L . squares.scm
[square 1] 
[square 2] [square 3] [square 4] [square 5] (1 9 25)
[square 6] [square 7] (1 9 25 49)
1011

The sieve of Eratosthenes

The sieve of Eratosthenes finds prime numbers: it takes the first number, which is prime, and removes all its multiples from the rest. With streams, the sieve can produce all primes, not only those below a limit.

primes.scm
(use-modules (streams))

(define (divisible? n d)
  (= (remainder n d) 0))

(define (sieve s)
  (let ((p (stream-car s)))
    (cons-stream p
                 (sieve (stream-filter (lambda (n) (not (divisible? n p)))
                                       (stream-cdr s))))))

(define primes (sieve (integers-from 2)))

(display (stream-head primes 15))
(newline)
(display (stream-ref primes 499))
(newline)

(define twin-primes
  (stream-filter (lambda (pair) (= (- (cadr pair) (car pair)) 2))
                 (stream-map list primes (stream-cdr primes))))

(display (stream-head twin-primes 6))
(newline)

sieve keeps the first element p and sieves the rest of the stream after filtering out the multiples of p. Each prime adds one more filter, so the stream of primes is a growing chain of lazy filters. stream-ref finds the 500th prime. The twin primes are pairs of primes that differ by 2; the program pairs each prime with the next one by mapping list over the stream and its tail, and keeps the pairs with a difference of 2.

$ guile -L . primes.scm
(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47)
3571
((3 5) (5 7) (11 13) (17 19) (29 31) (41 43))

Streams defined by themselves

Because the tail of a stream is computed later, a stream definition can refer to the stream itself. The elements that the tail needs are already there when it is forced.

fibs.scm
(use-modules (streams))

(define (add-streams a b)
  (stream-map + a b))

(define (scale-stream s factor)
  (stream-map (lambda (x) (* x factor)) s))

(define ones (cons-stream 1 ones))

(define naturals (cons-stream 0 (add-streams ones naturals)))

(define fibs
  (cons-stream 0 (cons-stream 1 (add-streams fibs (stream-cdr fibs)))))

(define powers-of-two (cons-stream 1 (scale-stream powers-of-two 2)))

(display (stream-head ones 5))
(newline)
(display (stream-head naturals 8))
(newline)
(display (stream-head fibs 12))
(newline)
(display (stream-ref fibs 100))
(newline)
(display (stream-head powers-of-two 11))
(newline)

ones is an infinite stream of ones whose tail is the stream itself. naturals starts with 0 and continues with the sum of ones and naturals, so each element is the previous one plus one. fibs adds the stream to its own tail: each Fibonacci number is the sum of the two before it. Thanks to memoization, the 100th number is computed with a hundred additions, not with the exponential tree recursion of the naive procedure. powers-of-two doubles every element of itself.

$ guile -L . fibs.scm
(1 1 1 1 1)
(0 1 2 3 4 5 6 7)
(0 1 1 2 3 5 8 13 21 34 55 89)
354224848179261915075
(1 2 4 8 16 32 64 128 256 512 1024)

Long chains of promises

Some lazy algorithms build a promise whose value is another promise, as in (delay (force ...)). Forcing such a chain nests one call to force in the next. With Guile's built-in force, a countdown written this way works for 10,000 steps, but at 100,000 steps Guile 3.0.7 stops with a stack overflow. R7RS solves this with delay-force, which Guile provides as lazy in SRFI 45.

lazy.scm
(use-modules (srfi srfi-45))

(define (countdown n)
  (if (= n 0)
      (delay 'liftoff)
      (lazy (countdown (- n 1)))))

(display (force (countdown 10)))
(newline)
(display (force (countdown 1000000)))
(newline)

(define (stream-from n)
  (lazy (eager (cons n (stream-from (+ n 1))))))

(define (stream-drop-while skip? s)
  (lazy (let ((pair (force s)))
          (if (skip? (car pair))
              (stream-drop-while skip? (cdr pair))
              s))))

(define big (force (stream-drop-while (lambda (n) (< n 1000000)) (stream-from 0))))
(display (car big))
(newline)
(display (car (force (cdr big))))
(newline)

SRFI 45 replaces delay and force and adds lazy and eager. lazy takes an expression that returns a promise, and force follows the whole chain in a loop, in constant space. eager wraps a value that is already computed. The countdown passes through a million promises. stream-from builds a stream in the SRFI 45 style, where the stream itself is a promise of a pair, and stream-drop-while skips the first million numbers. The R7RS library (scheme lazy) provides the same procedures under the names delay-force and make-promise, but importing it in a script prints warnings that it overrides the core bindings.

$ guile lazy.scm
liftoff
liftoff
1000000
1000001

SRFI 41 streams

Guile includes the SRFI 41 stream library. Its streams use promises of their own in the SRFI 45 style, so long chains are safe. It provides the procedures written above and many more, in the style of the list library.

library.scm
(use-modules (srfi srfi-41))

(define naturals (stream-from 0))

(display (stream->list (stream-take 5 naturals)))
(newline)
(display naturals)
(newline)

(define-stream (squares-from n)
  (stream-cons (* n n) (squares-from (+ n 1))))

(display (stream->list 6 (squares-from 1)))
(newline)
(display (stream->list (stream-filter even? (stream 1 2 3 4 5 6))))
(newline)
(display (stream-ref (stream-map * naturals naturals) 12))
(newline)
(display (stream-pair? naturals))
(display " ")
(display (stream-null? (stream)))
(newline)

stream-from is the stream of numbers from a start. stream-take returns a stream of the first elements, which stream->list converts to a list; with a count as its first argument, stream->list takes the elements itself. Displaying a stream shows the elements that have been computed so far, followed by an ellipsis. define-stream defines a procedure whose body is evaluated lazily, and stream-cons plays the role of cons-stream. stream builds a finite stream like list builds a list. stream-pair? and stream-null? test for a non-empty and an empty stream.

$ guile library.scm
(0 1 2 3 4)
#<stream 0 1 2 3 4 ...>
(1 4 9 16 25 36)
(2 4 6)
144
#t #t

Generating streams

SRFI 41 has procedures that generate streams from a rule instead of from a recursive definition. They mirror unfold from the SRFI 1 list library.

building.scm
(use-modules (srfi srfi-41))

(define powers (stream-iterate (lambda (x) (* x 2)) 1))
(display (stream->list 10 powers))
(newline)

(define (collatz n)
  (stream-unfold (lambda (n) n)
                 (lambda (n) (> n 0))
                 (lambda (n)
                   (cond ((= n 1) 0)
                         ((even? n) (quotient n 2))
                         (else (+ (* 3 n) 1))))
                 n))
(display (stream->list (collatz 6)))
(newline)
(display (stream-length (collatz 27)))
(newline)

(display (stream->list (stream-take-while (lambda (x) (< x 100)) powers)))
(newline)

(display (stream->list
          (stream-of (list a b c)
                     (c in (stream-range 1 30))
                     (b in (stream-range 1 c))
                     (a in (stream-range 1 b))
                     (= (+ (* a a) (* b b)) (* c c)))))
(newline)
(display (stream-fold + 0 (stream-take 100 (stream-from 1))))
(newline)

stream-iterate applies a procedure again and again to a start value. stream-unfold takes a procedure that maps a seed to an element, a test that says whether to continue, a procedure that computes the next seed, and the first seed. The Collatz sequence halves even numbers and maps odd numbers to 3n + 1 until it reaches 1; the program turns the 1 into a 0 to end the stream. The sequence from 27 has 112 elements. stream-take-while ends an infinite stream at the first element that fails a test. stream-of is a stream comprehension: it builds the Pythagorean triples from nested ranges and a condition. stream-fold combines the elements of a finite stream.

$ guile building.scm
(1 2 4 8 16 32 64 128 256 512)
(6 3 10 5 16 8 4 2 1)
112
(1 2 4 8 16 32 64)
((3 4 5) (6 8 10) (5 12 13) (9 12 15) (8 15 17) (12 16 20) (15 20 25) (7 24 25) (10 24 26) (20 21 29))
5050

Reading a file lazily

A stream can also come from input. A stream of lines reads the next line only when the program asks for it, so a search through a large file stops reading as soon as it has found what it wanted.

lines.scm
(use-modules (srfi srfi-41) (ice-9 rdelim))

(define lines-read 0)

(define-stream (line-stream port)
  (let ((line (read-line port)))
    (if (eof-object? line)
        stream-null
        (begin
          (set! lines-read (+ lines-read 1))
          (stream-cons line (line-stream port))))))

(define (warning? line)
  (string-prefix? "WARN" line))

(call-with-input-file "server.log"
  (lambda (port)
    (let ((warnings (stream-filter warning? (line-stream port))))
      (stream-for-each (lambda (line) (display line) (newline))
                       (stream-take 2 warnings)))))

(display "lines read: ")
(display lines-read)
(newline)

line-stream reads a line with read-line from the reading input article and counts the lines read. The program filters the stream for warnings and prints the first two. Although the log has ten lines, only five are read: the second warning is on line five. The whole stream is used inside call-with-input-file, because the port is closed when that procedure returns.

$ cat server.log
INFO server started on port 8080
INFO connected to database
WARN disk usage at 81%
INFO request GET /index.html
WARN slow response: 2.4 s
INFO request GET /scheme/
WARN disk usage at 85%
INFO request POST /login
ERROR database connection lost
INFO server stopped
$ guile lines.scm
WARN disk usage at 81%
WARN slow response: 2.4 s
lines read: 5

Source

Delayed Evaluation — GNU Guile Reference Manual

SRFI-41 — GNU Guile Reference Manual

SRFI 45: Primitives for Expressing Iterative Lazy Algorithms

In this article we have created promises with delay and evaluated them with force, computed values only when needed, built infinite streams with a cons-stream macro, mapped and filtered them, sieved prime numbers, defined streams in terms of themselves, forced long promise chains with SRFI 45, used the SRFI 41 library, and read a file lazily. The closures article builds generators with state, and the continuations article builds them with call/cc.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.