[plt-scheme] call/cc puzzle

From: Jon Rafkind (rafkind at cs.utah.edu)
Date: Sat Jan 17 14:22:00 EST 2009

Henk Boom wrote:
> 2009/1/17 Jos Koot <jos.koot at telefonica.net>:
>> Is that a quation or just a nice gesture?
>> Jos
> The latter. I had fun coming up with it and figuring out why it did
> what it did, and I thought maybe other people would as well. =)
I think I figured out at least part of it. Hope I don't spoil it for 

(let ([f (call/cc1 call/cc2)])
  (printf "f is ~a\n" f)
  (f (lambda (x) (printf "x is ~a\n" x))))

I wrote call/cc1 and call/cc2 to mean call/cc but so I could identify 
them in the explanation. The result of this prints

f is #<continuation>
f is #<procedure:/home/jon/tmp/x.ss:17:5>
x is #<procedure:/home/jon/tmp/x.ss:17:5>

The flow is this: call/cc1 passes its continuation to call/cc2 which 
invokes the first continuation with the second. So f is now equal to the 
continuation of call/cc2 and it prints #<continuation> as expected. Now 
f is invoked with the continuation of call/cc2 with (lambda (x) ...) 
which starts the computation at (let ([f ...]) ...) so f is now bound to 
(lambda (x) ...). Printing this results in <procedure>, and then the f 
[which is now (lambda (x) ...)] is applied to (lambda (x) ...) which 
prints #<procedure> again.

So at the end it does ((lambda (x) (printf "x is ~a\n" x)) (lambda (x) 
(printf "x is ~a\n" x))). Maybe this is obvious to some people but it 
took me at least 15 minutes to figure out.

Posted on the users mailing list.