Continuations in Scheme
The only way to create a continuation object in Scheme is to use
call-with-current-continuation
or call/cc
for short. This is a function built
right into Scheme. What it does is to take a snapshot of the current state of
the program and wrap it in a continuation object. The argument of call/cc
must
be a function f
that takes one argument. call/cc
calls f
with the
continuation object it has created. We now effectively have two continuations,
as illustrated in the figure below:
-
One continuation is the "normal" progression of the program. Since we just called
f
, this continuation starts by executingf
and all the functions thatf
itself calls. At some pointf
returns and the program continues from the point where we calledf
usingcall/cc
. We don't have an explicit value that represents this continuation, but it is what happens if we just run our program normally. -
The other continuation is the one captured by the continuation object created by
call/cc
and passed tof
. This continuation captures the computation starting from the point after we invokecall/cc
, that is, the same part of the program that gets executed afterf
returns in the "normal" continuation.
Now f
has two choices: It can just run to completion without ever doing
anything with the continuation object it was given. This leads to the normal
progression as if we had made an ordinary function call. The other choice is to
call the continuation it was given. In that case, f
aborts and the computation
continues immediately after call/cc
. The following figure illustrates this.
In effect, we can think about calling a continuation as a glorified goto
statement. Since deep down, at assembly level, all programs are composed of
function calls and goto statements, it shouldn't come as a surprise that
continuations as first-class objects are an extremely powerful tool that allows
us to build many different abstractions by hand. Let's look at a few examples.