ZetCode

Scheme continuations

last modified November 24, 2026 Guile 3.0

At every point of a running program there is some work left to do with the value being computed: add it to something, print it, return it to a caller. This remaining work is the continuation of that point. Most languages keep it hidden on the call stack. Scheme lets a program capture it as an ordinary procedure with call/cc. Calling that procedure abandons the current computation and continues from the captured point. With this single feature a program can build early exits, generators, coroutines, and backtracking. The examples run with GNU Guile 3.0.7.

Escaping from a loop

call/cc, short for call-with-current-continuation, takes a procedure of one argument. It calls this procedure with the current continuation, here named return. If the procedure returns normally, call/cc returns its value; if it calls return with a value, call/cc returns that value at once.

escape.scm
(define (first-negative numbers)
  (call/cc
   (lambda (return)
     (for-each (lambda (n)
                 (display "checking ")
                 (display n)
                 (newline)
                 (when (negative? n)
                   (return n)))
               numbers)
     #f)))

(display (first-negative '(3 8 -2 7 -5)))
(newline)
(display (first-negative '(1 2)))
(newline)

for-each has no way to stop in the middle of a list. Calling return jumps out of the loop and out of the inner lambda, and the value -2 becomes the result of the whole call/cc expression. The checks of 7 and -5 never run. When no negative number is found, the loop ends normally and the body returns #f.

$ guile escape.scm
checking 3
checking 8
checking -2
-2
checking 1
checking 2
#f

A continuation is a value

A continuation is a first-class value. It can be stored in a variable and called after call/cc has already returned. The program then goes back to the captured point and continues from there once more.

saved.scm
(define saved #f)
(define rounds 0)

(display "start")
(newline)

(display (+ 100 (call/cc (lambda (k)
                           (set! saved k)
                           1))))
(newline)

(set! rounds (+ rounds 1))

(when (< rounds 4)
  (saved (* rounds 10)))

(display "rounds: ")
(display rounds)
(newline)

The continuation of the call/cc expression is "add 100 to the value, display it, print a newline, and run the rest of the file". The first time, the procedure stores the continuation in saved and returns 1, so 101 is printed. Later, (saved 10) resumes that computation with 10 in place of the call/cc expression: 110 is printed and the following top-level forms run again. The variable rounds keeps its value across the jumps, because a continuation restores the control point, not the contents of variables. After three jumps the when test fails and the program ends.

$ guile saved.scm
start
101
110
120
130
rounds: 4

Leaving nested loops

An escape is most useful when the computation is deep: in recursion over a tree or in loops nested inside each other. A single call of the continuation leaves all the levels at once.

nested.scm
(define visited 0)

(define (tree-product tree)
  (call/cc
   (lambda (exit)
     (let walk ((t tree))
       (cond ((null? t) 1)
             ((pair? t) (* (walk (car t)) (walk (cdr t))))
             ((zero? t) (exit 0))
             (else (set! visited (+ visited 1))
                   t))))))

(display (tree-product '(2 (3 4) ((5) 6))))
(display ", numbers visited: ")
(display visited)
(newline)

(set! visited 0)
(display (tree-product '(2 (0 4) ((5) 6))))
(display ", numbers visited: ")
(display visited)
(newline)

(define grid
  (vector (vector 4 7 1)
          (vector 9 3 8)
          (vector 2 6 5)))

(define (grid-find grid value)
  (call/cc
   (lambda (found)
     (do ((row 0 (+ row 1)))
         ((= row (vector-length grid)) #f)
       (do ((col 0 (+ col 1)))
           ((= col (vector-length (vector-ref grid row))))
         (when (= (vector-ref (vector-ref grid row) col) value)
           (found (list row col))))))))

(display (grid-find grid 8))
(newline)
(display (grid-find grid 10))
(newline)

tree-product multiplies all numbers in a tree. A zero makes the product zero, so the walk stops at the first zero it finds instead of returning through every pending multiplication. The counter shows that only one number was visited in the second tree. grid-find searches a matrix with two do loops and returns the row and column of the value; when nothing is found, the outer loop ends with #f.

$ guile nested.scm
720, numbers visited: 5
0, numbers visited: 1
(1 2)
#f

Escape-only continuations

A full continuation can be re-entered at any time, which makes it costly to capture. When it is used only to jump out, Guile offers cheaper escape continuations in the (ice-9 control) module: call/ec works like call/cc, and let/ec binds the escape to a name for the body that follows.

escape-only.scm
(use-modules (ice-9 control))

(define (parse-all strings)
  (let/ec abort
    (map (lambda (s)
           (let ((n (string->number s)))
             (if n
                 n
                 (abort (string-append "not a number: " s)))))
         strings)))

(write (parse-all '("12" "7.5" "1/4")))
(newline)
(write (parse-all '("12" "seven" "1/4")))
(newline)

(define (sum-until-limit numbers limit)
  (call/ec
   (lambda (stop)
     (let loop ((xs numbers) (total 0))
       (cond ((null? xs) total)
             ((> (+ total (car xs)) limit) (stop total))
             (else (loop (cdr xs) (+ total (car xs)))))))))

(display (sum-until-limit '(10 20 30 40) 100))
(newline)
(display (sum-until-limit '(10 20 30 40) 55))
(newline)

(define stale #f)
(let/ec k (set! stale k))
(stale 1)

parse-all converts a list of strings to numbers and stops at the first string that is not a number, returning a message instead of the list. sum-until-limit adds numbers until the next one would exceed the limit. An escape continuation is only valid while its body is running. The last lines store one and call it after let/ec has finished; there is nothing left to escape from, and Guile reports an error without a file position.

$ guile escape-only.scm
(12 7.5 1/4)
"not a number: seven"
100
30
ERROR: In procedure abort: Abort to unknown prompt

Generators

Re-entering continuations allows two computations to take turns. A generator walks a data structure and hands out one element per call, keeping its place in the walk between calls. It needs two continuations: one to return a value to the caller and one to resume the walk.

generator.scm
(define (make-leaf-generator tree)
  (define caller #f)
  (define (walk t)
    (cond ((null? t) 'skip)
          ((pair? t) (walk (car t)) (walk (cdr t)))
          (else (call/cc
                 (lambda (rest)
                   (set! resume (lambda () (rest #f)))
                   (caller t))))))
  (define (resume)
    (walk tree)
    (caller 'done))
  (lambda ()
    (call/cc
     (lambda (k)
       (set! caller k)
       (resume)))))

(define next-leaf (make-leaf-generator '((a b) (c (d)) e)))

(display (next-leaf))
(display (next-leaf))
(display (next-leaf))
(newline)
(let loop ((leaf (next-leaf)))
  (display (list 'leaf leaf))
  (newline)
  (unless (eq? leaf 'done)
    (loop (next-leaf))))

(define (same-fringe? t1 t2)
  (let ((g1 (make-leaf-generator t1))
        (g2 (make-leaf-generator t2)))
    (let loop ()
      (let* ((x (g1))
             (y (g2)))
        (cond ((not (eqv? x y)) #f)
              ((eq? x 'done) #t)
              (else (loop)))))))

(display (same-fringe? '(1 (2 3) 4) '((1 2) (3 (4)))))
(newline)
(display (same-fringe? '(1 (2 3) 4) '(1 2 (4 3))))
(newline)

Each call of the generator saves the caller's continuation in caller and calls resume. The first time, resume starts the walk. At each leaf, the walk captures its own continuation, stores a procedure that resumes it in resume, and jumps to the caller with the leaf. The next call therefore continues the walk right after the previous leaf. When the walk ends, the generator returns done. same-fringe? compares the leaves of two trees of different shapes one by one, without building a list of either; it stops at the first difference.

$ guile generator.scm
abc
(leaf d)
(leaf e)
(leaf done)
#t
#f

dynamic-wind

Jumps with continuations can leave a block of code or enter it again from the outside. dynamic-wind takes three procedures without arguments: a before thunk, the body, and an after thunk. The before thunk runs every time control enters the body and the after thunk every time control leaves it, whether by a normal return or by a jump.

wind.scm
(define (show . items)
  (for-each display items)
  (newline))

(define (with-logging name thunk)
  (dynamic-wind
   (lambda () (show "enter " name))
   thunk
   (lambda () (show "leave " name))))

(show "result: "
      (with-logging "normal" (lambda () 42)))

(show "result: "
      (call/cc
       (lambda (escape)
         (with-logging "escape"
                       (lambda ()
                         (escape 'early)
                         (show "not printed"))))))

(define again #f)
(define passes 0)

(with-logging "re-entry"
              (lambda ()
                (call/cc (lambda (k) (set! again k)))
                (set! passes (+ passes 1))
                (show "body, pass " passes)))

(when (< passes 2)
  (again #f))

with-logging wraps a thunk in dynamic-wind. The normal call enters, returns 42, and leaves. In the second call, the body escapes with early, and the after thunk still runs before the escape completes. The third block saves a continuation inside the body and later jumps back into it from outside; the before thunk runs again on the way in. This is how Scheme guarantees cleanup, such as closing a file, when a computation is abandoned.

$ guile wind.scm
enter normal
leave normal
result: 42
enter escape
leave escape
result: early
enter re-entry
body, pass 1
leave re-entry
enter re-entry
body, pass 2
leave re-entry

Prompts

A continuation from call/cc captures the whole rest of the program. Guile also provides delimited continuations, which capture the computation only up to a prompt. call-with-prompt runs a thunk under a prompt tag, and abort-to-prompt jumps back to the prompt, passing the captured part of the computation to a handler as a procedure k.

prompts.scm
(define tag (make-prompt-tag 'yield))

(define (yield value)
  (abort-to-prompt tag value))

(define (make-generator producer)
  (define next (lambda () (producer) 'done))
  (lambda ()
    (call-with-prompt tag
      (lambda () (next))
      (lambda (k value)
        (set! next (lambda () (k #f)))
        value))))

(define (walk-leaves tree)
  (cond ((null? tree) #t)
        ((pair? tree) (walk-leaves (car tree)) (walk-leaves (cdr tree)))
        (else (yield tree))))

(define next-leaf
  (make-generator (lambda () (walk-leaves '((a b) (c (d)) e)))))

(let loop ((leaf (next-leaf)))
  (display leaf)
  (display " ")
  (unless (eq? leaf 'done)
    (loop (next-leaf))))
(newline)

(define next-square
  (make-generator (lambda ()
                    (do ((i 1 (+ i 1)))
                        ((> i 5))
                      (yield (* i i))))))

(let* ((first (next-square))
       (second (next-square)))
  (display (list first second))
  (newline))

(display
 (call-with-prompt tag
   (lambda () (+ 1 (yield 10)))
   (lambda (k value)
     (list value (k 5) (k 100)))))
(newline)

Here yield aborts to the prompt with a value. The handler in make-generator returns the value to the caller and saves k; the next call runs (k #f) under a fresh prompt, which resumes the producer after its yield. Unlike the call/cc generator, the producer is ordinary code that does not know about continuations, so any loop, like the do loop of squares, becomes a generator. The last expression shows that k is a normal procedure: it returns the value of the delimited computation (+ 1 []) and can be called more than once.

$ guile prompts.scm
a b c d e done 
(1 4)
(10 6 101)

Backtracking

Continuations can also go back in time to an earlier choice. The last example implements nondeterministic search: choose picks one of several values and remembers how to come back for the next one, and need rejects the current combination, which sends the program back to the most recent choice that still has alternatives.

amb.scm
(define fail-stack '())

(define (fail)
  (let ((back (car fail-stack)))
    (set! fail-stack (cdr fail-stack))
    (back #f)))

(define (choose choices)
  (call/cc
   (lambda (k)
     (for-each (lambda (choice)
                 (call/cc
                  (lambda (next)
                    (set! fail-stack (cons next fail-stack))
                    (k choice))))
               choices)
     (fail))))

(define (need condition)
  (unless condition
    (fail)))

(define (all-solutions thunk)
  (let ((results '()))
    (call/cc
     (lambda (done)
       (set! fail-stack (list (lambda (ignored) (done #f))))
       (set! results (cons (thunk) results))
       (fail)))
    (reverse results)))

(define numbers (iota 15 1))

(define (triple)
  (let* ((a (choose numbers))
         (b (choose numbers))
         (c (choose numbers)))
    (need (< a b))
    (need (= (+ (* a a) (* b b)) (* c c)))
    (list a b c)))

(display (all-solutions triple))
(newline)

For every value it tries, choose captures a continuation next that continues with the remaining values and pushes it on fail-stack. fail pops the latest one and calls it, so a failure resumes the loop inside the most recent choose. When a choice runs out of values, it fails too, going back one more level. all-solutions starts with a failure that ends the search, and after each solution it records the result and fails on purpose to look for the next. triple reads like a description of the problem: pick three numbers from 1 to 15 and require a Pythagorean triple with a < b.

$ guile amb.scm
((3 4 5) (5 12 13) (6 8 10) (9 12 15))

Source

Continuations — GNU Guile Reference Manual

Prompts — GNU Guile Reference Manual

In this article we have captured continuations with call/cc, escaped from loops and recursion, re-entered a saved continuation, used the cheaper escape continuations of (ice-9 control), built generators with call/cc and with prompts, guarded code with dynamic-wind, and searched for solutions by backtracking. The tail calls and iteration article covers the loops the escapes jump out of, and the closures article builds simpler generators that keep state in variables.

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.