ZetCode

Scheme closures

last modified November 24, 2026 Guile 3.0

A closure is a procedure together with the variables it can see at the place where it was created. When a lambda expression is evaluated, Scheme records the current bindings along with the code, and the procedure keeps using them even after the surrounding let or procedure call has finished. The higher-order procedures article returned procedures from make-adder; this article looks at why that works and combines closures with set! to keep state between calls. The examples run with GNU Guile 3.0.7.

Remembering the environment

The variables and binding article showed that Scheme uses lexical scope: a procedure sees the variables around its definition. A closure keeps those variables alive for as long as the procedure exists.

remember.scm
(define greet
  (let ((greeting "Hello there"))
    (lambda (name)
      (string-append greeting ", " name "!"))))

(display (greet "Peter"))
(newline)

(define (make-greeter greeting)
  (lambda (name)
    (string-append greeting ", " name "!")))

(define formal (make-greeter "Good evening"))
(define casual (make-greeter "Hi"))

(display (formal "Mrs. Novak"))
(newline)
(display (casual "Tom"))
(newline)

greeting is a local variable of a let, and the let ends as soon as the lambda has been created. Calling greet later still finds the string, because the closure holds on to the binding. make-greeter creates a new binding of greeting on every call, so formal and casual are two closures over different values built from the same code.

$ guile remember.scm
Hello there, Peter!
Good evening, Mrs. Novak!
Hi, Tom!

State with set!

A closure may also change the variables it captured. Combining a captured variable with set! gives a procedure that remembers something from one call to the next.

counter.scm
(define (make-counter)
  (let ((count 0))
    (lambda ()
      (set! count (+ count 1))
      count)))

(define clicks (make-counter))
(define visits (make-counter))

(clicks)
(clicks)
(display (clicks))
(newline)
(display (visits))
(newline)
(display (clicks))
(display " ")
(display (visits))
(newline)

Each call to make-counter creates a fresh count starting at 0 and returns a procedure that increments it. The two counters do not share anything: clicks reaches 3 and then 4, while visits counts its own calls. No code outside the closures can read or reset count.

$ guile counter.scm
3
1
4 2

Remembering progress

The captured state may be more than a counter. A stepper produces the next number of an arithmetic sequence on each call and keeps its position in between.

step.scm
(define (make-stepper start step)
  (let ((current start))
    (lambda ()
      (let ((value current))
        (set! current (+ current step))
        value))))

(define evens (make-stepper 0 2))
(define countdown (make-stepper 10 -3))

(define (take-n gen n)
  (if (= n 0)
      '()
      (let ((value (gen)))
        (cons value (take-n gen (- n 1))))))

(write (take-n evens 5))
(newline)
(write (take-n evens 3))
(newline)
(write (take-n countdown 4))
(newline)

The closure saves the current value in value, advances current by step, and returns the saved value. take-n calls a generator n times and collects the results. It calls the generator in a let before consing, because the order in which the arguments of cons are evaluated is unspecified. The second call on evens continues from 10, where the first one stopped. countdown counts down from 10 by 3.

$ guile step.scm
(0 2 4 6 8)
(10 12 14)
(10 7 4 1)

Generators

A generator is a procedure without arguments that returns the next value of a sequence on each call. The sequence may come from a list or may be computed as it goes, and it may even be infinite.

generator.scm
(define (make-list-generator lst)
  (lambda ()
    (if (null? lst)
        'done
        (let ((item (car lst)))
          (set! lst (cdr lst))
          item))))

(define next-colour (make-list-generator '(red green blue)))

(display (next-colour))
(display " ")
(display (next-colour))
(display " ")
(display (next-colour))
(display " ")
(display (next-colour))
(newline)

(define (make-fibonacci)
  (let ((a 0) (b 1))
    (lambda ()
      (let ((value a))
        (set! a b)
        (set! b (+ value b))
        value))))

(define fib (make-fibonacci))
(do ((i 0 (+ i 1)))
    ((= i 12))
  (display (fib))
  (display " "))
(newline)

make-list-generator captures its lst parameter and moves it forward with set! on each call; when the list is used up, it returns the symbol done. The Fibonacci generator keeps the last two numbers in a and b and has no end, so the do loop decides how many values to take.

$ guile generator.scm
red green blue done
0 1 1 2 3 5 8 13 21 34 55 89 

Private state

Several procedures created in the same environment share its variables. This gives data that only those procedures can reach. A bank account is the classic example: the balance is changed only through deposits and withdrawals.

account.scm
(define (make-account balance)
  (define (deposit amount)
    (set! balance (+ balance amount))
    balance)
  (define (withdraw amount)
    (if (> amount balance)
        "insufficient funds"
        (begin
          (set! balance (- balance amount))
          balance)))
  (define (current) balance)
  (list deposit withdraw current))

(define acc (make-account 100))
(define deposit (car acc))
(define withdraw (cadr acc))
(define balance (caddr acc))

(display (deposit 50))
(newline)
(display (withdraw 30))
(newline)
(display (withdraw 500))
(newline)
(display (balance))
(newline)

(define other (make-account 10))
(display ((caddr other)))
(newline)

make-account defines three internal procedures that all refer to the parameter balance, and returns them in a list. The top-level names are bound to the elements of the list. withdraw refuses to go below zero, and there is no other way to change the balance. A second account has its own balance; its current procedure, the caddr of the list, is called with no arguments and returns 10.

$ guile account.scm
150
120
insufficient funds
120
10

Closures created in loops

A closure captures a binding, not a value. Whether closures made in a loop see different values depends on whether each pass creates new bindings or the loop reuses one variable.

loops.scm
(define (make-procs)
  (do ((i 1 (+ i 1))
       (procs '() (cons (lambda () i) procs)))
      ((> i 3) (reverse procs))))

(write (map (lambda (p) (p)) (make-procs)))
(newline)

(define (make-procs-shared)
  (let ((i 1) (procs '()))
    (let loop ()
      (when (<= i 3)
        (set! procs (cons (lambda () i) procs))
        (set! i (+ i 1))
        (loop)))
    (reverse procs)))

(write (map (lambda (p) (p)) (make-procs-shared)))
(newline)

do binds its variables anew on each iteration, so each of the three lambdas captures its own i and they return 1, 2, and 3. make-procs-shared creates a single i in a let and updates it with set!. All three closures capture that one binding, and when they are called, it holds 4, the value that ended the loop.

$ guile loops.scm
(1 2 3)
(4 4 4)

Callbacks

A callback is a procedure handed to other code to be called later. Closures make good callbacks because each one carries its own settings. The program registers three handlers that react to sensor readings.

callbacks.scm
(define handlers '())

(define (on-reading handler)
  (set! handlers (cons handler handlers)))

(define (report value)
  (for-each (lambda (h) (h value)) (reverse handlers)))

(define (make-logger prefix)
  (lambda (value)
    (display prefix)
    (display value)
    (newline)))

(define (make-alarm limit)
  (lambda (value)
    (when (> value limit)
      (display "  alarm: above ")
      (display limit)
      (newline))))

(define total 0)

(on-reading (make-logger "reading: "))
(on-reading (make-alarm 30))
(on-reading (lambda (value) (set! total (+ total value))))

(for-each report '(21 25 34 28))
(display "sum of readings: ")
(display total)
(newline)

on-reading stores a handler, and report calls every handler with a value, in the order of registration. The logger remembers its prefix and the alarm its limit, so each handler knows how to react without extra arguments. The third handler is a lambda that adds every reading to the top-level total.

$ guile callbacks.scm
reading: 21
reading: 25
reading: 34
  alarm: above 30
reading: 28
sum of readings: 108

Limiting calls

A closure can wrap another procedure and control when it runs. The next program creates a procedure that does its work only once, and one that refuses to run after a given number of calls.

once.scm
(define (make-once f)
  (let ((done #f) (result #f))
    (lambda ()
      (unless done
        (set! result (f))
        (set! done #t))
      result)))

(define load-settings
  (make-once (lambda ()
               (display "loading settings...")
               (newline)
               '((theme . dark) (size . 12)))))

(write (load-settings))
(newline)
(write (load-settings))
(newline)

(define (make-limited f limit)
  (let ((left limit))
    (lambda (x)
      (if (> left 0)
          (begin (set! left (- left 1)) (f x))
          'limit-reached))))

(define try-code (make-limited (lambda (code) (= code 1234)) 3))
(for-each (lambda (code)
            (write (try-code code))
            (display " "))
          '(1111 2222 3333 1234))
(newline)

make-once runs f on the first call and stores the result; later calls return the stored value without running f again, so the loading message appears once. make-limited counts down the allowed calls in left. The code checker accepts three attempts, and the fourth is refused even though it holds the right code. The attempts are made with for-each because it visits the list in order, while the order in which map calls its procedure is not specified.

$ guile once.scm
loading settings...
((theme . dark) (size . 12))
((theme . dark) (size . 12))
#f #f #f limit-reached 

Memoization

Memoization stores the results of a procedure so that a repeated call with the same argument is answered from the store. The cache lives in a closure, here as an association list of argument and result pairs.

memo.scm
(define (memoize f)
  (let ((cache '()))
    (lambda (n)
      (let ((hit (assv n cache)))
        (if hit
            (cdr hit)
            (let ((result (f n)))
              (set! cache (cons (cons n result) cache))
              result))))))

(define calls 0)

(define slow-fib
  (lambda (n)
    (set! calls (+ calls 1))
    (if (< n 2) n (+ (slow-fib (- n 1)) (slow-fib (- n 2))))))

(display (slow-fib 25))
(display " in ")
(display calls)
(display " calls")
(newline)

(set! calls 0)
(set! slow-fib (memoize slow-fib))
(display (slow-fib 25))
(display " in ")
(display calls)
(display " calls")
(newline)

(set! calls 0)
(display (slow-fib 90))
(display " in ")
(display calls)
(display " calls")
(newline)

memoize looks up the argument with assv and computes the result only on a miss. The plain tree-recursive Fibonacci makes 242785 calls for (slow-fib 25). After slow-fib is replaced with its memoized version, the recursive calls inside the body also go through the cache, because they refer to the top-level name: each number is computed only once, in 26 calls. The cache survives between calls, so (slow-fib 90) needs only the 65 values that are not yet stored.

$ guile memo.scm
75025 in 242785 calls
75025 in 26 calls
2880067194370816120 in 65 calls

Source

About Closure — GNU Guile Reference Manual

R7RS: the Revised7 Report on Scheme

In this article we have seen how a closure keeps the variables of its environment, kept state between calls with set!, written steppers and generators, hidden an account balance behind three procedures, compared closures made in do loops with closures over a shared variable, used closures as callbacks, and wrapped procedures to limit and memoize their calls. The higher-order procedures article covers passing and returning procedures, and the association lists article explains the data structure used as the memoization cache. The object-oriented programming with closures article builds objects that answer messages from closures like the account.

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.