Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Continuations and Tail Calls

call/cc and Escapes

Understand continuations: what the rest of the computation is, how call/cc captures it, early exit from loops, and runnable JavaScript stand-ins for escaping continuations.

Every expression is evaluated with an invisible question hanging over it: "and then what?" When you evaluate (+ 1 (* 2 3)), the sub-expression (* 2 3) runs with the continuation "take the result and add 1 to it". A continuation is that "rest of the computation", and Scheme lets you grab it as an ordinary value with call-with-current-continuation, usually written call/cc.

Most languages hide continuations. Scheme exposes them, and from that single feature you can build exceptions, early exit, generators, coroutines and backtracking. This lesson covers the first and most common use: escaping. Later lessons build on it. Previously we made loops safe with tail calls; continuations are about control flow beyond plain calls and returns.

The Racket and Scheme code here is read-only: our site cannot run it. The JavaScript blocks are labelled stand-ins that model escaping continuations with exceptions. JavaScript cannot capture a continuation that is re-entered later, so those parts are explained in words.

What call/cc does

(call/cc f) calls f with one argument: the current continuation, packaged as a function k. Calling (k v) abandons whatever is happening and makes the whole call/cc expression return v.

RACKET
(+ 1 (call/cc (lambda (k) (* 2 3))))        ; => 7, k never used
(+ 1 (call/cc (lambda (k) (+ 10 (k 5)))))   ; => 6

In the second line, (k 5) throws away the pending (+ 10 ...) and returns 5 to the point where call/cc was called, so the outer addition gives 6. The k here behaves like return in a C function, but you can place it anywhere, not only at function boundaries.

Racket spells the same idea call-with-current-continuation or call/cc, and also offers the more restricted, cheaper call-with-escape-continuation (let/ec) when you only need to escape.

Early exit from a loop

The most practical use: stop searching as soon as you find something.

RACKET
(define (find-first pred lst)
  (call/cc
   (lambda (return)
     (for-each (lambda (x)
                 (when (pred x) (return x)))
               lst)
     #f)))

(find-first even? '(1 3 6 7 8)) ; => 6

for-each has no way to break. Here return is the continuation of the whole find-first call, so invoking it from inside the loop exits both the loop and the function at once. If nothing matches, for-each finishes normally and #f is returned.

The stand-in below models an escape with a JavaScript exception: callEC hands the body a function that throws a unique token, and callEC catches exactly that token.

JS Stand-in: escaping continuation with an exception

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Escaping from several levels

Because k is just a value, you can pass it down into helper functions. The helper does not need to know how to propagate a "stop" signal back up: it simply calls k. This replaces a lot of boilerplate in code that would otherwise return special values at every level.

RACKET
(define (product lst)
  (call/cc
   (lambda (done)
     (let loop ([lst lst])
       (cond [(null? lst) 1]
             [(zero? (car lst)) (done 0)]   ; skip the rest of the work
             [else (* (car lst) (loop (cdr lst)))])))))

(product '(2 3 0 4 5)) ; => 0

When a zero is found, all the pending multiplications on the stack are discarded and 0 is returned immediately. That is an exception-like exit, and in fact exceptions in many languages can be built from continuations.

Here is the same shape in JavaScript, counting how much work was skipped:

JS Stand-in: product with an early exit

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Beyond escaping: re-entry

A full continuation can be called after call/cc has already returned, even more than once. That re-enters a computation that seemed finished. For example, you can store k in a variable and call it later to "go back" and run the rest of the expression again with a different value.

RACKET
(define saved #f)
(+ 100 (call/cc (lambda (k) (set! saved k) 1)))   ; => 101
;; later: (saved 5) re-runs "add 100" with 5

Re-entry is what makes generators, coroutines and backtracking possible (next lesson). It is also powerful and dangerous: code that appears to run once can run again. Racket mitigates this with continuation prompts (call-with-continuation-prompt) and delimited continuations (shift/reset-style), which capture only the part of the computation up to a marked point, making them far easier to reason about.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a continuation?

    A continuation represents everything that remains to be done once the current expression produces its value.
  2. 2. What does (+ 1 (call/cc (lambda (k) (+ 10 (k 5))))) return?

    (k 5) abandons the pending (+ 10 ...) and makes the call/cc expression return 5, so the outer expression is 1 + 5 = 6.
  3. 3. Why is call/cc useful for breaking out of for-each?

    Invoking the continuation captured outside the loop returns a value from the entire surrounding expression.
  4. 4. What extra power does a full continuation have compared with an escape-only one?

    A full continuation can re-enter a computation later, which enables generators and backtracking. Escape-only continuations are valid just while their call/cc is still active.

Summary

  • A continuation is "the rest of the computation"; call/cc hands it to you as a function.
  • Calling the continuation returns a value from the call/cc expression and discards pending work.
  • The most common use is early exit from loops and deep recursion.
  • Full continuations can be re-entered later; Racket also provides escape-only and delimited variants that are easier to control.
  • A JavaScript exception with a unique token models the escape (not the re-entry).

Next: Generators and Coroutines