2

我完全迷失了 Scheme 中的通话继续。有人可以帮我这个例子吗?

 #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 年的结果。

4

3 回答 3

3

I get this

> (myfunction number? '(18 16 2015 2))
4
> (a-continuation 2014)
2018

but this "to the best of my knowledge" explanation should still work.

(I expected the continuation to add 1 to its argument. I was wrong, so I'm trying to explain this to myself, too.)

If you remove the continuation parts, myfunction is a function that counts for how many elements the predicate what? holds.

Playing around a little in the REPL/interaction window,

> (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

One can suspect from this pattern that the continuation adds to its argument the number of elements that myfunction found.

This is my explanation of why this is so:

If you view each call/cc as a "hole" that you can fill in later by calling the captured continuation, the first one is

(+ 1 <hole>)

the second

(+ 1 (+ 1 <hole>))

and so on, creating a "chain" of additions, one for each time the predicate holds.
(I.e. capturing the entire recursion that's "waiting" for the continuation to continue, not just the innermost call.)

So

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

creates something that looks like

(+ 1 (+ 1 (+ 1 (+ 1 <hole>))))

and when you call the continuation,

(a-continuation 2014)

you evaluate

(+ 1 (+ 1 (+ 1 (+ 1 2014))))

which is, of course, 2018.

(Disclaimer: This may be completely wrong.)

于 2015-01-28T13:40:30.543 回答
0

这真的很令人困惑。但也许一个更简单的例子可以帮助(取自这里

(define return #f) 

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

当你评估(+ 1 (call/cc ...))你得到2. (call/cc ...)因为零件的返回值为1. 现在我们已经设置returncont. call/cc在这个范围内,cont是一个接受 1 个参数的过程。当被调用时,它将评估该参数。这是有趣的部分,当您评估过程时,评估会在call/cc. 因此,当您调用It时(return 22),它将评估为.22(+ 1 (call/cc ...))23

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

于 2015-01-28T15:27:39.607 回答
0

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

当打电话给你时,(a-continuation 2014)你回到处理2而不是递归你告诉继续的答案是2014,因此你得到(+ 1 (+ 1 (+ 1 (+ 1 2014)))) ; ==> 2018

于 2015-01-29T21:57:13.887 回答