I am reading The scheme programming language and seeing this example in continuation section:
(((call/cc (lambda (k) k)) (lambda (x) x)) "HEY!") => "HEY!"
I cannot figure out why this expression evaluating to "HEY!"
According to the CSE 341 lecture notes:
(call/cc expr)
does the following:
- Captures the current continuation.
- Constructs a function
C
that takes one argument, and applies the current continuation with that argument value. - Passes this function as an argument to
expr
--- i.e., it invokes(expr C)
. - Returns the result of evaluating
(expr C)
, unlessexpr
callsC
, in which case the value that is passed toC
is returned.
So, in this example (((call/cc (lambda (k) k)) (lambda (x) x)) "HEY!") => "HEY!"
the current continuation of
call/cc
is(lambda (v) ((v (lambda (x) x)) "HEY!")
the constructed function
C
is(lambda (y) ((lambda (v) ((v (lambda (x) x)) "HEY!")) y))
invokes
((lambda (x) x) C)
returns the result of evaluating
((lambda (x) x) C)
, which isC
itself
Therefore, (call/cc (lambda (k) k))
evaluates to C
. The whole expression will be:
(((lambda (y)
((lambda (v)
((v (lambda (x) x)) "HEY!")) y)) (lambda (x) x)) "HEY!")
i.e. ((C (lambda (x) x)) "HEY!")
, which is ("HEY!" "HEY!")
.
This will result in an exception: Wrong type to apply: "HEY!"
, meaning applying a non-function value "HEY!".
Where am I wrong?