From: Ramakrishnan Muthukrishnan Date: Sun, 30 May 2010 12:53:46 +0000 (+0530) Subject: a much beautiful way to solve 1.43 using recursion X-Git-Url: https://git.rkrishnan.org/components/com_hotproperty/?a=commitdiff_plain;h=d28d1e53f2d99b4024e3f9310fd56c2777677409;p=sicp.git a much beautiful way to solve 1.43 using recursion --- diff --git a/src/sicp/ex1_43.clj b/src/sicp/ex1_43.clj index 5c8e7ea..ae29dff 100644 --- a/src/sicp/ex1_43.clj +++ b/src/sicp/ex1_43.clj @@ -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