2.36
(define s (list (list 1 2 3)(list 4 5 6)(list 7 8 9)(list 10 11 12)))
(define (accumulate-n op init seqs)
(if (null? (car seqs)) null
(cons (accumulate op init (map# (lambda(x) (car x)) seqs))
(accumulate-n op init (map# (lambda(x) (cdr x)) seqs)))))
2.38
;> (fold-right / 1 (list 1 2 3))
;3/2
;> (fold-left / 1 (list 1 2 3))
;1/6
;> (fold-right list null (list 1 2 3))
;(1 (2 (3 ())))
;> (fold-left list null (list 1 2 3))
;(((() 1) 2) 3)
; (fold-right op i (a b c)) = (op a (op b (op c i)))
; (fold-left op i (a b c)) = (op (op (op i a) b) c)
要 fold-right 和 fold-left 得到相同的结果,显然需要 op 满足交换律。
2.39
(define (reverse-1 seqs)
(fold-right (lambda(x y) (append y (list x))) null seqs))
(define (reverse-2 seqs)
(fold-left (lambda(x y) (cons y x)) null seqs))