Question

I'm having some trouble understanding this piece of code that my professor used as example:

(define saved-cont #f)  

(define (test-cont)
     (let ((x 0))
      (call/cc
       (lambda (k)     
        (set! saved-cont k))) 

      (set! x (+ x 1))
      (display x)
      (newline)))

If we run for the first time (test-cont) what does k contain?

Note: I'm using R6RS Scheme.

Was it helpful?

Solution

call/cc calls the given function with the current continuation as its sole argument. Thus, k here is the current continuation. When you call it with a value, the call/cc will return with the value you gave. (Though, since you're not using call/cc's return value in your code above, and since R6RS allows zero-valued returns in that case, you can just call saved-cont with no arguments and still do what you expect.)

Here, basically, every time you call (saved-cont), the code below the call/cc will run again. Thus, x will increment, and its new value will display.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top