在“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对吗?提前谢谢!
最好的祝福