Chapter 1, Building Abstractions with Procedures

Section - Formulating Abstractions with Higher-Order Procedures

Exercise 1.46


Here is our iterative-improve procedure:

1
2
3
4
5
6
7
8
9
(define (iterative-improve improve good-enough?)
   (define (iter x)
       (if (good-enough? x)
           x
           (iter (improve x))
       )
   )
   iter
)

Implementation of sqrt using iterative-improve:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(define (sqrt x)
   (
       (iterative-improve
            (lambda (y)
                     (average y (/ x y))
            )   
            (lambda (y)
                     (< (abs (- (square y) x)) 0.001)
            )  
       )
       1.0 ; initial guess
   )
)

; Helper procedures
(define (square x) (* x x))
(define (average a b)
    (/ (+ a b) 2)
)  

Implementation of fixed-point using iterative-improve:

1
2
3
4
5
6
7
8
9
(define tolerance 0.00001)
(define (fixed-point f initial-guess)
  ((iterative-improve  
          f 
          (lambda (x)
                  (< (abs (- x (f x))) tolerance)
          )          
  ) initial-guess)
)