2.38这个题目特别有意思,能比较深的理解什么是左侧优先右侧优先。先看看实现代码
;;满足交换律,即操作函数的参数可相互交换,其结果不变
(defn fold-right[op initial sequences]
(if (empty? sequences)
initial
(op (first sequences)
(accumulate op initial (rest sequences))
)))
(defn fold-left [op initial sequences]
(defn iter[result rests]
(if (empty? rests)
result
(iter (op result (first rests))
(rest rests))
))
(iter initial sequences)
)
(fold-right / 1 (list 1 2 3)) ;;3/2
(fold-left / 1 (list 1 2 3)) ;;1/6
(fold-right list nil (list 1 2 3)) ;;(1 (2 (3 nil)))
(fold-left list nil (list 1 2 3)) ;;(((nil 1) 2) 3)
执行结果呢已经写在了注释里,要想让op的操作左右相同,必须满足交换律。通俗点说,就是两个参数交换,不影响计算结果,比如加法,乘法 与运算 或运算等等。