]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_32.clj
Solution to 4.30. Extremely enlightening!
[sicp.git] / src / sicp / ex1_32.clj
1 (ns sicp.ex1_32
2   (:use [sicp utils]
3         [clojure.contrib test-is]))
4
5 (defn accumulate [combiner null-value term a next b]
6   (if (> a b)
7     null-value
8     (combiner (term a)
9               (accumulate combiner null-value term (next a) next b))))
10
11 (def sum (fn [a b] (accumulate + 0 identity a inc b)))
12
13 (def sum-cube (fn [a b] (accumulate + 0 cube a inc b)))
14
15 (def prod (fn [a b] (accumulate * 1 identity a inc b)))
16
17 (defn iaccumulate [combiner null-value term a next b]
18   (iter combiner null-value term a next b null-value))
19
20 (defn iter [combiner null-value term a next b result]
21   (if (> a b)
22     result
23     (iter combiner null-value term (next a) next b (combiner (term a) result))))
24
25 (def isum (fn [a b] (iaccumulate + 0 identity a inc b)))
26
27 (def isum-cube (fn [a b] (iaccumulate + 0 cube a inc b)))
28
29 (def iprod (fn [a b] (iaccumulate * 1 identity a inc b)))
30
31 (deftest test-sum-of-integers-from-1-to-10
32   (is (= (sum 1 10) (reduce + (range 1 11)))))
33
34 (deftest test-sum-cube-of-integers-from-1-to-10
35   (is (= (sum-cube 1 10) (reduce + (map cube (range 1 11))))))
36
37 (deftest test-prod-of-ints-from-1-to-10
38   (is (= (prod 1 10) (reduce * (range 1 11)))))
39
40 (deftest test-isum-of-integers-from-1-to-10
41   (is (= (isum 1 10) (reduce + (range 1 11)))))
42
43 (deftest test-isum-cube-of-integers-from-1-to-10
44   (is (= (isum-cube 1 10) (reduce + (map cube (range 1 11))))))
45
46 (deftest test-iprod-of-ints-from-1-to-10
47   (is (= (iprod 1 10) (reduce * (range 1 11)))))