简体   繁体   中英

Example of Continuations in Scheme

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM