]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_18.clj
Merge branch 'master' of github.com:vu3rdd/sicp
[sicp.git] / src / sicp / ex1_18.clj
1 (ns sicp.ex1_18
2   (:use [sicp utils]
3         [clojure.contrib trace test-is]))
4
5 ;; exercise 1.18: iterative multiply thru addition
6 ;; the idea is to keep a state variable.
7 (defn fast-mult-iter [a b k]
8   (cond (= b 0) k
9         (even? b) (fast-mult-iter (twice a) (half b) k)
10         :else (fast-mult-iter a (- b 1) (+ k a))))
11
12 (defn fast-mult-new [a b]
13   (fast-mult-iter a b 0))
14
15 ;; (comment
16 ;; user> (dotrace [fast-mult-new fast-mult-iter] (fast-mult-new 2 3))
17 ;; TRACE t2915: (fast-mult-new 2 3)
18 ;; TRACE t2916: |    (fast-mult-iter 2 3 0)
19 ;; TRACE t2917: |    |    (fast-mult-iter 2 2 2)
20 ;; TRACE t2918: |    |    |    (fast-mult-iter 4 1 2)
21 ;; TRACE t2919: |    |    |    |    (fast-mult-iter 4 0 6)
22 ;; TRACE t2919: |    |    |    |    => 6
23 ;; TRACE t2918: |    |    |    => 6
24 ;; TRACE t2917: |    |    => 6
25 ;; TRACE t2916: |    => 6
26 ;; TRACE t2915: => 6
27 ;; 6
28 ;; )