]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex1_6.clj
Solution to 4.33. This had been difficult to get right, though conceptually it was
[sicp.git] / src / sicp / ex1_6.clj
1 (ns sicp.ex1_6
2   (:use [sicp utils]
3         [clojure.contrib trace test-is]))
4
5 ;; exercise 1.6
6 ;; Alyssa P. Hacker doesn't see why if needs to be provided as a special form.
7 ;; ``Why can't I just define it as an ordinary procedure in terms of cond?''
8 (defn new-if [predicate then-clause else-clause]
9   (cond predicate then-clause
10         :else else-clause))
11
12 (new-if (= 3 2) 0 5)  ; 5
13 (new-if (= 1 1) 0 5)  ; 0
14
15 ;; Delighted, Alyssa uses new-if to rewrite the square-root program:
16
17 (defn sqrt-iter [guess x]
18   (new-if (good-enough? guess x)
19           guess
20           (sqrt-iter (improve guess x)
21                      x)))
22
23 ;; what happens when Alyssa attempts to use this to compute square roots? Explain.
24 (comment
25   Since `new-if' is a function, when it is called from sqrt-iter, the parameters
26   are evaluated before it gets called. good-enough? will return a false unless
27   the guess and x are almost the same. guess evaluated to the initial value of
28   guess. sqrt-iter gets evaluated, but gets into an infinite loop. The predicate
29   will have no effect.)