-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathex2.38-fold-left.scm
40 lines (29 loc) · 1 KB
/
ex2.38-fold-left.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
(define (fold-left op initial sequence)
(define (iter result rest)
(if (null? rest)
result
(iter (op result (car rest))
(cdr rest))))
(iter initial sequence))
(define (fold-right op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(fold-right op initial (cdr sequence)))))
(fold-right / 1 (list 1 2 3)) ; 1.5
(fold-left / 1 (list 1 2 3)) ; 1/6
(fold-right list (list ) (list 1 2 3)) ;
; (1 (2 (3 ())))
(fold-left list (list ) (list 1 2 3))
; (((() 1) 2) 3)
;Give a property that op should satisfy to guarantee that fold-right and fold-left will produce the same values for any sequence.
; commutative law and associative law
; prove:
; fold-left with initial and sequance of a b c:
; (op (op (op initial a) b) c)
; ((initial op a) op b) op c
; fold-right with initial and sequance of a b c:
; (op a (op b (op c initial)))
; (a op (b op (c op initial)))
; with commutative law and associative law:
; ((initial op a) op b) op c === (a op (b op (c op initial)))