First of all, (define foo (lambda (args) body)) is just the Scheme idiom for defining functions. It's normally written `(define (foo args) body)` or Python `def foo(args): body`.
In a little more detail, let's take a function that looks like this; I'll use the shorter syntax to avoid line noise:
(define (sum-of-squares bound)
0)
(print (sum-of-squares 100)) ;; prints "0"
Now let's see what happens with a continuation:
(define (sum-of-squares bound)
(call/cc the-receiver)) ;; will return whatever is passed to current continuation
;; for now, it will jump to the receiver, passing the whole call stack to it
(define (the-receiver cont)
(cont 18))
(sum-of-squares 100) ;; will start executing sum-of-squares, then jump to the-receiver, passing it the call stack
;; then, the-receiver will jump back into sum-of-squares, replacing the value of the whole `call/cc` form with the value 18
;; which will be returned to the top level
This use is similar to the following Python code:
def sum_of_squares(bound):
try:
the_receiver()
except MyContinuation as e:
return e.Value
def the_receiver():
raise MyContinuation(18)
To show some more power of what this can do, let's save the continuation to a global var and call it a few times:
(define some-continuation '())
(define (sum-of-squares bound)
(call/cc the-receiver)) ;; will return whatever is passed to current continuation
;; for now, it will jump to the receiver, passing the whole call stack to it
(define (the-receiver cont)
(set! some-continuation cont)) ;; the receiver stores the value of cont into some-continuation and returns control to the top level.
;; at this point, sum-of-squares and anything that was calling it has NOT finished executing:
;; it's frozen in the continuation
(display (sum-of-squares 100)) ;;sets some-continuation to the continuation, doesn't print anything
(some-continuation 18) ;; prints 18
(some-continuation 200) ;; prints 200
(display (+ 100 (sum-of-squares 100))) ;;sets some-continuation to a new vale, doesn't print anything
(some-continuation 18) ;; prints 118
(some-continuation 200) ;; prints 300