; ======================================================================
;
; Structure and Interpretation of Computer Programs
; (trial answer to excercises)
;
; 计算机程序的构造和解释(习题试解)
;
; created: code17 08/19/05
; modified:
; (保持内容完整不变前提下,可以任意转载)
; ======================================================================
;; SICP No.2.38
;; 原文中的fold-left定义有些繁琐,修改如下(同样是迭代)
(define (fold-left op initial sequence)
(if (null? sequence)
initial
(fold-left op (op initial (car sequence)) (cdr sequence))))
(define fold-right accumulate)
> (fold-right / 1 (list 1 2 3))
3/2
> (fold-left / 1 (list 1 2 3))
1/6
> (fold-right list () (list 1 2 3))
(1 (2 (3 ())))
> (fold-left list () (list 1 2 3))
(((() 1) 2) 3)
;; 易证,当op满足交换律和结合律时
;; 即 (op a b) = (op b a))
;; (op (op a b) c) = (op a (op b c)) 时
;; fold-left和fold-right可以保证产生同样的结果