]> git.rkrishnan.org Git - sicp.git/blobdiff - src/sicp/ex1_43.clj
Better explanation of the unless procesure if it is not defined
[sicp.git] / src / sicp / ex1_43.clj
index 5c8e7ea93c36eb2029d09756b737bfdf01559786..ae29dffab86c2b4cfe08260466bfe1b4471663cd 100644 (file)
@@ -4,13 +4,19 @@
        [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)
@@ -19,3 +25,6 @@
 (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