很困惑scheme中的fold-left和fold-right到底是如何求值的。先看下面的代碼spa
> (fold-right / 1 (list 1 2 3)) 3/2 > (fold-left / 1 (list 1 2 3)) 1/6
很明顯,對於+和*這種有交換律的運算,這2者的計算結果是沒有什麼區別的,可是對於-和/這樣的沒有交換律的運算,區別就很大了。對於上面2個調用,能夠分別作以下展開rest
> (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能夠分別作以下重定義,來自sicpcode
(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))