2

在“The Scheme Programming Language 4th Edition”中,有一个例子如下:


(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)(λ(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对吗?提前谢谢!

最好的祝福

4

1 回答 1

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
于 2012-07-04T14:53:31.547 回答