From: Ramakrishnan Muthukrishnan Date: Wed, 5 May 2010 13:11:29 +0000 (+0530) Subject: some minor re-arrangements X-Git-Url: https://git.rkrishnan.org/(%5B%5E?a=commitdiff_plain;h=967523eeb5c71d134937fb6b58e668d4dd5041c1;p=sicp.git some minor re-arrangements --- diff --git a/src/sicp/ex1_32.clj b/src/sicp/ex1_32.clj index 369b677..a2fc28b 100644 --- a/src/sicp/ex1_32.clj +++ b/src/sicp/ex1_32.clj @@ -22,6 +22,12 @@ result (iter combiner null-value term (next a) next b (combiner (term a) result)))) +(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-sum-of-integers-from-1-to-10 (is (= (sum 1 10) (reduce + (range 1 11))))) @@ -31,12 +37,6 @@ (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))))) diff --git a/src/sicp/utils.clj b/src/sicp/utils.clj index 6ebbe24..0ee9355 100644 --- a/src/sicp/utils.clj +++ b/src/sicp/utils.clj @@ -2,7 +2,7 @@ (defn square [x] (* x x)) -(defn myabs +(defn abs "find absolute value of x" [x] (if (< x 0) (- x) x)) @@ -16,6 +16,25 @@ (defn half [x] (/ x 2)) +(defn divides? [a b] + (= (rem b a) 0)) + +(defn- find-divisor [n test-divisor] + (cond (> (square test-divisor) n) n + (divides? test-divisor n) test-divisor + :else (find-divisor n (inc test-divisor)))) + +(defn- smallest-divisor [n] + (find-divisor n 2)) + +(defn prime? [n] + (= (smallest-divisor n) n)) + +(defn gcd [a b] + (if (= b 0) + a + (gcd b (rem a b)))) + (defmacro microbench " Evaluates the expression n number of times, returning the average time spent in computation, removing highest and lowest values.