]> git.rkrishnan.org Git - sicp.git/blobdiff - src/sicp/ex1_43.clj
Solutions to 4.27, 4.28 and 4.29.
[sicp.git] / src / sicp / ex1_43.clj
index f7cb7ff80bf7d083a9f485a8d1c54cb0a51d8a3b..ae29dffab86c2b4cfe08260466bfe1b4471663cd 100644 (file)
@@ -4,11 +4,27 @@
        [sicp ch1_3]
        [sicp ex1_42]))
 
-(defn repeated-1 [f1 f2 m]
+;; older iterative implementation
+(defn- repeated-i [f1 f2 m]
   (cond (= m 0) f1
        (= m 1) f2
-       :else (repeated-1 f1 (compose f2 f1) (- m 1))))
+       :else (repeated-i f1 (compose f2 f1) (- m 1))))
+
+(defn repeated-iterative [f n]
+  (repeated-i f (compose f f) (- n 1)))
 
 (defn repeated [f n]
-  (repeated-1 f (compose f f) (- n 1)))
+  (if (= n 1)
+    f
+    (compose f (repeated f (- n 1)))))
+
+(deftest test-repeated-square-twotimes-of-5
+  (is (= ((repeated square 2) 5)
+        625)))
+
+(deftest test-repeated-square-twotimes-of-2
+  (is (= ((repeated square 2) 2)
+        16)))
 
+(deftest test-repeated-inc-of-2-by-5
+  (is (= ((repeated inc 5) 2) 7)))
\ No newline at end of file