let块中call / cc的延续是什么

时间:2016-09-14 14:31:52

标签: scheme racket continuations callcc

我遇到了一个使用call / cc解释Continuations的片段。在下面提供的代码片段中,call / cc调用的fn的延续是整个let块,还是call / cc下面的行?也有人可以解释为什么不提供整个let块作为延续?

#lang racket
(define resume-test-3 #f)

(define test-3 (lambda ()
   ; the let defines a variable i local to the lambda, and 
   ; sets its value to 0
   (let ((i 0))
     ;
     (call/cc (lambda (k) (set! resume-test-3 k)))
     ;
     ; The next time the-continuation is called, we start here.
     (displayln "I am back ")
     (set! i (+ i 1))
     ; and return the value i
     i
     )
    ))

(test-3)
(resume-test-3)
(resume-test-3)

2 个答案:

答案 0 :(得分:1)

call/cc表达式的延续包括 call/cc表达式后面的表达式。 如果我们添加(displayln "Entering let"),我们可以看到 调用延续不会导致"输入let" 打印。

#lang racket
(define resume-test-3 #f)

(define test-3 (lambda ()
   ; the let defines a variable i local to the lambda, and 
   ; sets its value to 0
   (let ((i 0))
     (displayln "Entering let")
     ;
     (call/cc (lambda (k) (set! resume-test-3 k)))
     ;
     ; The next time the-continuation is called, we start here.
     (displayln "I am back ")
     (set! i (+ i 1))
     ; and return the value i
     (displayln "Leaving let")
     i)))

(test-3)
(resume-test-3)
(resume-test-3)

输出:

Entering let
I am back 
Leaving let
1
I am back 
Leaving let
2
I am back 
Leaving let
3

答案 1 :(得分:1)

实现将整个事物重写为Continuation Passing Style(= CPS):

(define resume-test-3-cps #f)
(define test-3-cps
  (lambda (k)
    ((lambda (kl i) ; this is the "let"
       ((lambda (tk1) (tk1 (set! resume-test-3-cps tk1)))
        (lambda (not-used)
          ((lambda (tk2) (tk2 (displayln "I am back ")))
           (lambda (not-used)
             ((lambda (tk3) (tk3 (set! i (+ i 1))))
              (lambda (not-used)
                ((lambda (tk4) (tk4 (displayln "Leaving let")))
                 (lambda (not-used)
                   ((lambda (tk5) (tk5 i))
                    kl))))))))))
     k 0))) ; variables to "let"

;; top level have barriers, don't know how to simulate them
;; doing full CPS here will make an infinite loop
(test-3-cps values)
(resume-test-3-cps values)
(resume-test-3-cps values)

请注意,即使不使用call/cc也能正常工作。多数民众赞成因为call/cc只是一种获得CPS功能而无需在CPS中编写的方法。当你知道它是如何运作的时候,没有多少魔力。