Continuations

Like hygenic macros, continuations are one of the more difficult parts of Scheme to understand, as well as one of the most hotly debated features. Conceptually, when an expression in Scheme is evaluated, a special object is created, called a continuation which represents the subsequent steps in the computation. This object can be reified and saved by the form (call-with-current-continuation) , which is usually shortened to (call/cc). When (call/cc) is used to call a function, it passes that function the continuation which existed at the time of the call; if the function then invokes this continuation, program execution is halted and restarted at the point after the (call/cc) call was made. For example,

   (define call/cc call-with-current-continuation)

   (define (continued x) 
     (call/cc (lambda (return)
                (let loop ((y 0))
                  (if (eq? x y) (return)
                      (begin 
                        (display y)
                        (newline)
                        (display "next? ")
                        (loop (read))))))))
  

In this example, the loop runs until a '5' is entered, at which point it escapes back to the caller. (call/cc) is most often used to escape from nested loops, but it is a completely general mechanism, which can be used for a variety of purposes, including implementing multitasking.

Contents Previous Next