blob: 40b4a1317b85ba6c6dee4374208b451c68b9cf9b (
plain) (
blame)
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
38
39
40
41
42
43
44
45
46
47
|
;;;; License: CC0-1.0
(define-module (net ricketyspace sicp two thirtyeight)
#:export (fold-left
fold-right))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (fold-right op initial sequence)
(accumulate op initial sequence))
(define (fold-left op initial sequence)
(define (iter result rest)
(if (null? rest)
result
(iter (op result (car rest))
(cdr rest))))
(iter initial sequence))
;;; Guile REPL
;;;
;;; scheme@(guile-user)> ,use (net ricketyspace sicp two thirtyeight)
;;; scheme@(guile-user)> (fold-right / 1.0 (list 1 2 3))
;;; $2 = 1.5
;;; scheme@(guile-user)> (fold-left / 1.0 (list 1 2 3))
;;; $12 = 0.16666666666666666
;;; scheme@(guile-user)> (fold-right list '() (list 1 2 3))
;;; $13 = (1 (2 (3 ())))
;;; scheme@(guile-user)> (fold-left list '() (list 1 2 3))
;;; $14 = (((() 1) 2) 3)
;;; scheme@(guile-user)> (fold-right * 1 (list 1 2 3))
;;; $19 = 6
;;; scheme@(guile-user)> (fold-left * 1 (list 1 2 3))
;;; $20 = 6
;;;
;;;
;;; Conclusion: When the result produced by applying `op` on
;;; `sequence` is independent of the order in which `op` is applied to
;;; each element of the `sequence` then fold-right and fold-left will
;;; yield the same result.
;;;
|