From a37c0ce780939eb6decf85284ca6effcbd4c6cdc Mon Sep 17 00:00:00 2001 From: Ramakrishnan Muthukrishnan Date: Wed, 5 May 2010 16:33:21 +0530 Subject: [PATCH] solution to 1.32 --- src/sicp/ex1_32.clj | 47 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/sicp/ex1_32.clj diff --git a/src/sicp/ex1_32.clj b/src/sicp/ex1_32.clj new file mode 100644 index 0000000..369b677 --- /dev/null +++ b/src/sicp/ex1_32.clj @@ -0,0 +1,47 @@ +(ns sicp.ex1_32 + (:use [sicp utils] + [clojure.contrib test-is])) + +(defn accumulate [combiner null-value term a next b] + (if (> a b) + null-value + (combiner (term a) + (accumulate combiner null-value term (next a) next b)))) + +(def sum (fn [a b] (accumulate + 0 identity a inc b))) + +(def sum-cube (fn [a b] (accumulate + 0 cube a inc b))) + +(def prod (fn [a b] (accumulate * 1 identity a inc b))) + +(defn iaccumulate [combiner null-value term a next b] + (iter combiner null-value term a next b null-value)) + +(defn iter [combiner null-value term a next b result] + (if (> a b) + result + (iter combiner null-value term (next a) next b (combiner (term a) result)))) + +(deftest test-sum-of-integers-from-1-to-10 + (is (= (sum 1 10) (reduce + (range 1 11))))) + +(deftest test-sum-cube-of-integers-from-1-to-10 + (is (= (sum-cube 1 10) (reduce + (map cube (range 1 11)))))) + +(deftest test-prod-of-ints-from-1-to-10 + (is (= (prod 1 10) (reduce * (range 1 11))))) + +(def isum (fn [a b] (iaccumulate + 0 identity a inc b))) + +(def isum-cube (fn [a b] (iaccumulate + 0 cube a inc b))) + +(def iprod (fn [a b] (iaccumulate * 1 identity a inc b))) + +(deftest test-isum-of-integers-from-1-to-10 + (is (= (isum 1 10) (reduce + (range 1 11))))) + +(deftest test-isum-cube-of-integers-from-1-to-10 + (is (= (isum-cube 1 10) (reduce + (map cube (range 1 11)))))) + +(deftest test-iprod-of-ints-from-1-to-10 + (is (= (iprod 1 10) (reduce * (range 1 11))))) -- 2.45.2