Exercise 1.6

Given this new definition of the if special form:

1
2
3
(define (new-if predicate then-clause else-clause)
   (cond (predicate then-clause)
         (else else-clause)))

It is used in the following program:

1
2
3
4
5
(define (sqrt-iter guess x)
   (new-if (good-enough? guess x)
           guess
           (sqrt-iter (improve guess x)
                      x)))

What happens is that the operands of the new-if are evaluated, which means that the computation will not finish due to a recursive invocation chain of the sqrt-iter procedure, as illustrated here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
(sqrt 4)

(sqrt-iter 1.0 4)

(new-if (good-enough? 1.0 4)
        4
        (sqrt-iter (improve 1.0 4)
                   4)))
(new-if #f
        4
        (new-if (good-enough? 2.5 4)
                2.5
                (sqrt-iter (improve 2.5 4)
                           4)))
(new-if #f
        4
        (new-if #f
                2.5
                (new-if (good-enough? 2.05 4)
                        2.05
                        (sqrt-iter (improve 2.05 4)
                                   4)))
                                 .
                                 .
                                 .
Creative Commons License
This work, unless otherwise expressly stated, is licensed under a Creative Commons Attribution 2.0 UK: England & Wales License.

Tags: ,

Leave a Reply

CAPTCHA Image

Powered by WP Hashcash

Please wrap all source codes with [code][/code] tags.