2.38 Exercise 2.38
> (fold-right / 1 (list 1 2 3)) 3/2
First (/ 3 2) is computed, then this is divided by 1, making 3/2 the final answer.
> (define (fold-left op initial sequence) (define (iter result rest) (if (null? rest) result (iter (op result (car rest)) (cdr rest)))) (iter initial sequence)) > (fold-left / 1 (list 1 2 3)) 1/6
However, here 1 is divided by 2 first, and then this is divided by 3, making 1/6 the final answer.
> (fold-right list nil (list 1 2 3)) (mcons 1 (mcons (mcons 2 (mcons (mcons 3 (mcons '()))))))
First, 3 is consed with nil. Then, 2 is consed with this. Then, 1 is consed with this. Because a number is always consed with a list, this produces a list structure.
(fold-left list nil (list 1 2 3)) |
(((() 1) 2) 3) |
First, nil is consed with 1. Then, this is consed with 2. Then, this is consed with 3. Because a pair is always consed with a number, this produces the opposite of a list structure.
fold-left and fold-right will produce the same result if op is commutative.