]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_33.clj
Solution to 4.33. This had been difficult to get right, though conceptually it was
[sicp.git] / src / sicp / ex1_33.clj
1 (ns sicp.ex1_33
2   (:use [sicp utils]
3         [clojure.contrib test-is]))
4
5 (defn filtered-accumulate [predicate? combiner null-value term a next b]
6   (if (> a b)
7     null-value
8     (combiner (term (if (predicate? a)
9                       a
10                       null-value))
11               (filtered-accumulate predicate?
12                                    combiner
13                                    null-value
14                                    term
15                                    (next a)
16                                    next
17                                    b))))
18
19 (deftest test-filtered-sum-of-primes-from-1-to-10
20   (is (= (filtered-accumulate prime? + 0 identity 1 inc 10)
21          (reduce + (filter prime? (range 1 11))))))
22
23 (deftest test-filtered-prod-of-relative-primes-of-10
24   (is (= (filtered-accumulate #(= 1 (gcd % 10)) * 1 identity 1 inc 10)
25          (reduce * (filter #(= 1 (gcd % 10)) (range 1 11))))))