Next: , Previous: , Up: scheme overview   [Index]


3.1.13 Continuations

Whenever a Scheme expression is evaluated there is a continuation wanting the result of the expression. The continuation represents an entire (default) future for the computation. For example, informally the continuation of 3 in the expression

(+ 1 3)

adds 1 to it. Normally these ubiquitous continuations are hidden behind the scenes and programmers do not think much about them. On rare occasions, however, a programmer may need to deal with continuations explicitly.

The call-with-current-continuation procedure allows Scheme programmers to do that by creating a procedure that reinstates the current continuation. Control features

The call-with-current-continuation procedure accepts a procedure, calls it immediately with an argument that is an escape procedure. This escape procedure can then be called with an argument that becomes the result of the call to call-with-current-continuation. That is, the escape procedure abandons its own continuation, and reinstates the continuation of the call to call-with-current-continuation.

In the following example, an escape procedure representing the continuation that adds ‘1’ to its argument is bound to escape, and then called with ‘3’ as an argument. The continuation of the call to escape is abandoned, and instead the ‘3’ is passed to the continuation that adds ‘1’:

(+ 1 (call-with-current-continuation
       (lambda (escape)
         (+ 2 (escape 3)))))
⇒ 4

An escape procedure has unlimited extent: It can be called after the continuation it captured has been invoked, and it can be called multiple times. This makes call-with-current-continuation significantly more powerful than typical non–local control constructs such as exceptions in other languages.


Next: , Previous: , Up: scheme overview   [Index]