scheme中的fold-left和fold-right
很困惑scheme中的fold-left和fold-right究竟是如何求值的。先看下面的代码
> (fold-right / 1 (list 1 2 3)) 3/2 > (fold-left / 1 (list 1 2 3)) 1/6
很明显,对于+和*这种有交换律的运算,这2者的计算结果是没有什么区别的,但是对于-和/这样的没有交换律的运算,区别就很大了。对于上面2个调用,可以分别做如下展开
> (fold-right / 1 (list 1 2 3)) 3/2 > (/ 1 (/ 2 (/ 3 1))) 3/2 > (fold-left / 1 (list 1 2 3)) 1/6 > (/ (/ (/ 1 3) 2) 1) 1/6
其实fold-right和fold-left可以分别做如下重定义,来自sicp
(define (fold-right op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(fold-right op initial (cdr sequence)))))
(define (fold-left op initial sequence)
(define (iter result rest)
(if (null? rest)
result
(iter (op result (car rest))
(cdr rest))))
(iter initial sequence))