The essence of call-with-concurrent-continuation
, or call/cc
for short, is the ability to grab checkpoints, or continuations, during the execution of a program. Then, you can go back to those checkpoints by applying them like functions.
Here's a simple example where the continuation isn't used:
> (call/cc (lambda (k) (+ 2 3)))
5
If you don't use the continuation, it's hard to tell the difference. Here's a few where we actually use it:
> (call/cc (lambda (k) (+ 2 (k 3))))
3
> (+ 4 (call/cc (lambda (k) (+ 2 3))))
9
> (+ 4 (call/cc (lambda (k) (+ 2 (k 3)))))
7
When the continuation is invoked, control flow jumps back to where the continuation was grabbed by call/cc
. Think of the call/cc
expression as a hole that gets filled by whatever gets passed to k
.
list-iter
is a substantially more complex use of call/cc
, and might be a difficult place to begin using it. First, here's an example usage:
> (define i (list-iter '(a b c)))
> (i)
a
> (i)
b
> (i)
c
> (i)
list-ended
> (i)
list-ended
Here's a sketch of what's happening:
list-iter
returns a procedure of no arguments i
.
- When
i
is invoked, we grab a continuation immediately and pass it to control-state
. When that continuation, bound to return
, is invoked, we'll immediately return to whoever invoked i
.
- For each element in the list, we grab a new continuation and overwrite the definition of
control-state
with that new continuation, meaning that we'll resume from there the next time step 2 comes along.
- After setting up
control-state
for the next time through, we pass the current element of the list back to the return
continuation, yielding an element of the list.
- When
i
is invoked again, repeat from step 2 until the for-each
has done its work for the whole list.
- Invoke the
return
continuation with 'list-ended
. Since control-state
isn't updated, it will keep returning 'list-ended
every time i
is invoked.
As I said, this is a fairly complex use of call/cc
, but I hope this is enough to get through this example. For a gentler introduction to continuations, I'd recommend picking up The Seasoned Schemer.