Exercise 1.46. Several of the numerical methods described in this chapter are instances of an extremely general computational strategy known as iterative improvement. Iterative improvement says that, to compute something, we start with an initial guess for the answer, test if the guess is good enough, and otherwise improve the guess and continue the process using the improved guess as the new guess. Write a procedure iterative-improve that takes two procedures as arguments: a method for telling whether a guess is good enough and a method for improving a guess. Iterative-improve should return as its value a procedure that takes a guess as argument and keeps improving the guess until it is good enough. Rewrite the sqrt procedure of section 1.1.7 and the fixed-point procedure of section 1.3.3 in terms of iterative-improve.
iterative-improve 将会接受两个过程作为参数,一个是 good-enough?,一个是 improve。这两个过程分别接受一个参数,即一个 guess。good-enough? 将会对 guess 进行评估,improve 将会返回一个更好的 guess。
这样的设计决定了当我们要定义 sqrt(或者其他基于 iterative-improve 过程的过程) 时,我们必须将 good-enough? 和 improve 定义为内部块,这样才能访问到该过程中的信息。
(define (iterative-improve good-enough? improve)
(define (iter guess)
(if (good-enough? guess)
guess
(iter (improve guess))))
iter)
(define (new-sqrt x)
(define (good-enough? guess)
(< (abs (- (square guess) x)) 0.001))
(define (improve guess)
(* 1/2 (+ guess (/ x guess))))
((iterative-improve good-enough? improve) 1.0))
(define (fixed-point f first-guess)
(define (close-enough? guess)
(< (abs (- guess (f guess))) 0.00001))
(define (improve guess)
(f guess))
((iterative-improve close-enough? improve) first-guess))