]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex2_38.clj
Lazy version of evaluator and tests.
[sicp.git] / src / sicp / ex2_38.clj
1 (ns sicp.ex2_38
2   (:use [clojure.test]
3         [sicp [ch2-2 :only (accumulate)]
4               [ex2_36 :only (accumulate-n)]]))
5
6 ;; The accumulate procedure is also known as fold-right, because it combines
7 ;; the first element of the sequence with the result of combining all the elements
8 ;; to the right. There is also a fold-left, which is similar to fold-right, except
9 ;; that it combines elements working in the opposite direction:
10 (def fold-right accumulate)
11
12 (defn fold-left [op initial sequence]
13   (if (nil? sequence)
14     initial
15     (fold-left op
16                (op initial (first sequence))
17                (next sequence))))
18
19 ;; What are the values of
20 (comment
21   "answers inlined")
22
23 (fold-right / 1 (list 1 2 3))
24 ;;=> 3/2
25
26 (fold-left / 1 (list 1 2 3))
27 ;;=> 1/6
28
29 (fold-right list nil (list 1 2 3))
30 ;;=> (1 (2 (3 nil)))
31
32 (fold-left list nil (list 1 2 3))
33 ;;=> (((nil 1) 2) 3)