[英]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? 如果我们第一次运行(test-cont)
, k
包含什么?
Note: I'm using R6RS Scheme. 注意:我正在使用R6RS方案。
call/cc
calls the given function with the current continuation as its sole argument. call/cc
使用当前延续作为其唯一参数来调用给定函数。 Thus, k
here is the current continuation. 因此,这里的k
是当前的延续。 When you call it with a value, the call/cc
will return with the value you gave. 当您使用值调用它时, call/cc
将返回您提供的值。 (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.) (但是,由于在上面的代码中没有使用call/cc
的返回值,并且由于R6RS在这种情况下允许零值返回,因此您可以不带任何参数地调用saved-cont
,并且仍然可以做您期望的事情。 )
Here, basically, every time you call (saved-cont)
, the code below the call/cc
will run again. 在这里,基本上,每次调用(saved-cont)
, call/cc
下面的代码将再次运行。 Thus, x
will increment, and its new value will display. 因此, x
将递增,并显示其新值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.