Scheme 呼叫延续CC-in方案

Scheme 呼叫延续CC-in方案,scheme,callcc,continuation,Scheme,Callcc,Continuation,我完全不知道该怎么继续通话。有人能帮我举个例子吗 #lang scheme (define a-continuation '*dummy-value*) (define (myfunction what? l) (cond ((null? l) 0) ((what? (car l)) (+ 1 (call/cc (lambda (f) (set! a-continuation f)

我完全不知道该怎么继续通话。有人能帮我举个例子吗

 #lang scheme


(define a-continuation '*dummy-value*)

(define (myfunction what? l)
  (cond ((null? l) 0)
        ((what? (car l)) 
         (+ 1 (call/cc (lambda (f)
                         (set! a-continuation f)
                         (myfunction what? (cdr l))))))
        (else (myfunction what? (cdr l)))))

(myfunction number? '(18 16 2015 2))

(a-continuation 2014)           
我理解第一个结果(3),但我不理解2017年的结果。

我明白了

> (myfunction number? '(18 16 2015 2))
4
> (a-continuation 2014)
2018
但这一“据我所知”的解释仍然有效

(我原以为续篇会给它的论点加上1。我错了,所以我也试着给自己解释一下。)

如果删除延续部分,
myfunction
是一个计算谓词
what?
包含多少元素的函数

在REPL/interaction窗口中玩一会儿

> (myfunction number? '(1))
1
> (a-continuation 1)
2
> (a-continuation 2)
3

> (myfunction number? '(1 2 3 4 5 6 7 8 9 10))
10
> (a-continuation 1)
11
> (a-continuation 2)
12
> (a-continuation 3)
13

> (myfunction even? '(1 2 3 4 5 6 7 8 9 10))
5
> (a-continuation 1)
6
> (a-continuation 2)
7
> (a-continuation 3)
8
从这个模式可以怀疑,continuation在其参数中添加了
myfunction
找到的元素数

以下是我对原因的解释:

如果您将每个
call/cc
视为一个“漏洞”,以后可以通过调用捕获的延续来填补,那么第一个漏洞是

(+ 1 <hole>)
创建看起来像

(+ 1 (+ 1 (+ 1 (+ 1 <hole>))))
你评估

(+ 1 (+ 1 (+ 1 (+ 1 2014))))
当然是2018年


(免责声明:这可能是完全错误的。)

这可能会令人困惑。但也许一个更简单的例子会有所帮助(摘自:

(定义返回#f)
(+1(电话/抄送)
(续)
(设置!返回继续)
1))) ;;  2
(返回22)
> 23
当您计算
(+1(call/cc…)
时,您会得到
2
。因为
(call/cc…)的返回值
部分是
1
。现在我们在
call/cc
中将
return
设置为
cont
。在这个范围内,
cont
是一个接受1个参数的过程。调用时,它将计算到该参数。有趣的是,当您计算该过程时,计算将在
的位置恢复>调用/cc
。因此,当您调用
(返回22)
时,它将在
中计算为
22
(+1(调用/cc…)
,结果是
23

希望这是清楚的。在我链接到的页面中还有其他更复杂的示例。

调用
(myfunction number?'(18 16 2015 2))时
您将把
a-continuation
设置为每次迭代的继续,以及在处理
18
16
、和
2015
和处理
2
后的最后一次迭代


调用
(a-continuation 2014)
时,您返回到
2
的处理过程,但不是递归,而是告诉继续的答案是
2014
,因此您得到
(+1(+1(+2014)));==>2018

您是对的@molbdnilo。在call/cc中,
f
是一个带有一个参数的过程。该参数是返回值。当您调用该过程时,您(绑定到
a-continuation
)在您的示例中,它将返回其参数
2014
。这将在上面进行评估。您唯一忘记的是
0
myfunction
在调用
null?
列表时返回。谢谢。我理解您的示例,但我不理解我的示例。我认为我应该有(+1(2014),所以2015年,但我得到2018年。
myfunction
的执行仍在继续。您设置的每个循环
a-continuation
tu都有一个新值。因此,对于每个递归,您得到
(+1…
),最后一个递归得到0。因此,对于
什么?
为真的每个元素,您将2014添加到1。看看是否有帮助。
(+ 1 (+ 1 (+ 1 (+ 1 <hole>))))
(a-continuation 2014)
(+ 1 (+ 1 (+ 1 (+ 1 2014))))
(define return #f) 

(+ 1 (call/cc 
       (lambda (cont) 
         (set! return cont) 
         1))) ;; <--- (+ 1 1)
 > 2
 (return 22)
 > 23