From: Ramakrishnan Muthukrishnan Date: Sat, 10 Apr 2010 17:44:35 +0000 (+0530) Subject: Added solution to 1.18. It is really really elegant problem and solution! X-Git-Url: https://git.rkrishnan.org/pf/content/en/service/about.html?a=commitdiff_plain;h=3853351fd0edd46ab600a1b6b68e2bd8a18a2a57;p=sicp.git Added solution to 1.18. It is really really elegant problem and solution! --- diff --git a/chapter1/ch1_2.clj b/chapter1/ch1_2.clj index ed57832..0cf3c55 100644 --- a/chapter1/ch1_2.clj +++ b/chapter1/ch1_2.clj @@ -510,4 +510,29 @@ TRACE t2494: => -0.39980345741334 (* 2 x)) (defn half [x] - (/ x 2)) \ No newline at end of file + (/ x 2)) + +;; exercise 1.18: iterative multiply thru addition +;; the idea is to keep a state variable. +(defn fast-mult-new [a b] + (fast-mult-iter a b 0)) + +(defn fast-mult-iter [a b k] + (cond (= b 0) k + (even? b) (fast-mult-iter (twice a) (half b) k) + :else (fast-mult-iter a (- b 1) (+ k a)))) + +(comment +user> (dotrace [fast-mult-new fast-mult-iter] (fast-mult-new 2 3)) +TRACE t2915: (fast-mult-new 2 3) +TRACE t2916: | (fast-mult-iter 2 3 0) +TRACE t2917: | | (fast-mult-iter 2 2 2) +TRACE t2918: | | | (fast-mult-iter 4 1 2) +TRACE t2919: | | | | (fast-mult-iter 4 0 6) +TRACE t2919: | | | | => 6 +TRACE t2918: | | | => 6 +TRACE t2917: | | => 6 +TRACE t2916: | => 6 +TRACE t2915: => 6 +6 +)