我的CPS是对的?

时间:2012-07-04 07:39:10

标签: scheme continuations continuation-passing

“方案编程语言第4版”中的

,有如下例子:


(define product
  (lambda (ls)
    (call/cc
      (lambda (break)
        (let f ([ls ls])
          (cond
            [(null? ls) 1]
            [(= (car ls) 0) (break 0)]
            [else (* (car ls) (f (cdr ls)))]))))))
(产品'(1 2 3 4 5))=> 120

(产品'(7 3 8 0 1 9 5))=> 0

以后它将在3.3中转换为CPS,如下所示


(define product
  (lambda (ls k)
    (let ([break k])
      (let f ([ls ls] [k k])
        (cond
          [(null? ls) (k 1)]
          [(= (car ls) 0) (break 0)]
          [else (f (cdr ls)
                   (lambda (x)
                     (k (* (car ls) x))))])))))
(产品'(1 2 3 4 5)(lambda(x)x))=> 120

(乘积'(7 3 8 0 1 9 5)(λ(x)x))=> 0

我想自己做,相应的CPS如下


 (define (product ls prod break)
    (cond
      ((null? ls)
       (break prod))
      ((= (car ls) 0)
       (break 0))
      (else
        (product (cdr ls) (* prod (car ls)) break))))
(乘积'(1 2 3 4 5)1(λ(x)x))=> 120

(乘积'(1 2 0 4 5)1(λ(x)x))=> 0

我想问一下我的CPS是对的吗? Ť 提前谢谢!

最佳观点

1 个答案:

答案 0 :(得分:1)

我认为这是正确的实施方式:

(define inside-product #f)  ;; to demonstrate the continuation

(define (product ls prod break)
  (cond
    ((null? ls)
     (begin
       (set! inside-product prod)
       (prod 1)))
    ((= (car ls) 0)
     (break 0))
    (else
     (product (cdr ls) (lambda (x) (prod (* (car ls) x))) break))))

(define identity (lambda (x) x))

CPS的想法是跟踪递归。

> (product (list 1 2 3) identity identity)
6
> (inside-product 4)
24