我一直在阅读call-with-current-continuation
,特别是在Scheme中,并且在许多网站上阅读了各种文章。但是,我仍然不了解使用call-with-current-continuation
时控制流如何工作。
例如,给定下面的附加代码,如何调用连续性?何时调用该连续性,控件如何流过此过程的主体?
(define call/cc call-with-current-continuation)
(define showit (lambda (a b)
(begin (display a) (display b) (display " "))))
(define f
(lambda (n)
(let ((p (call/cc (lambda (k) k))))
(begin
(showit ’f= n)
p))))
此外,当使用((f 2) (f 4))
运行此过程时,它会产生如下所示的无限循环:
有人能解释无限循环背后的原因吗? 注意:将Drracket与R5RS一起使用
答案 0 :(得分:0)
Call/cc 返回一个继续周围计算的函数。当它被调用时,控制被返回到函数被取出的地方,并带有一个赋予函数的值。
在示例中,(let ((p (call/cc (lambda (k) k)))) ...)
,p 被赋予了一个延续函数。如果随后调用 p 为 (p 3)
,则控件将返回到 let
形式,就像之前的 (let ((p 3)) ...)
一样。
((f 2) (f 4))
处理 (f 2) 和 (f 4) 的延续,导致无限循环。我试图解释以下流程:
=> ((f 2) (f 4))
=> (f 2) ;; first (f 2)
call/cc returns the current continuation (lets say "cc1") into p
display f=2
return cc1
=> (cc1 (f 4))
=> (f 4) ;; first (f 4)
call/cc returns the current continuation cc2 into p
display f=4
return cc2
=> (cc1 cc2)
cc1 goes back to the first (f 2), but call/cc returns now cc2 into p
display f=2
returns cc2 from the first (f 2)
=> (cc2 (f 4))
=> (f 4) ;; second (f 4)
call/cc returns cc3 into p
display f=4
return cc3
=> (cc2 cc3)
cc2 goes back to the first (f 4), but p gets cc3
display f=4
returns cc3 from the first (f 4)
=> (cc1 cc3)
cc1 goes back to the first (f 2), but p gets cc3
display f=2
returns cc3 from the first (f 2)
=> (cc3 (f 4))
=> (f 4) ;; third (f 4)
display f=4
<= cc4
=> (cc3 cc4)
=> (f 4) ;; second again
display f=4
<= cc4
=> (cc2 cc4)
=> (f 4) ;; first again
display f=4
<= cc4
=> (cc1 cc4)
=> (f 2) ;; first again
display f=2
<= cc4
=> (cc4 (f 4))
=> (f 4) ;; fourth (f 4)
display f=4
<= cc5
...so on