Blob


1 (define tolerance 0.00001)
2 (define (fixed-point f first-guess)
3 (define (close-enough? v1 v2)
4 (< (abs (- v1 v2)) tolerance))
5 (define (try guess)
6 (let ((next (f guess)))
7 (if (close-enough? guess next)
8 next
9 (try next))))
10 (try first-guess))
12 (define (average x y)
13 (/ (+ x y) 2.0))
14 (define (average-damp f)
15 (lambda (x) (average x (f x))))
16 (define (fixed-point-of-transform g transform guess)
17 (fixed-point (transform g) guess))
18 (define (sqrt x)
19 (fixed-point-of-transform (lambda (y) (/ x y))
20 average-damp
21 1.0))
22 (define (cube-root x)
23 (fixed-point-of-transform (lambda (y) (/ x (square y)))
24 average-damp
25 1.0))
27 (define (compose f g)
28 (lambda (x)
29 (f (g x))))
31 (define (test-case actual expected)
32 (load-option 'format)
33 (newline)
34 (format #t "Actual: ~A Expected: ~A" actual expected))
36 (define (square x) (* x x))
37 (define (inc x) (1+ x))
38 ;; (test-case ((compose square inc) 6) 49)
40 (define (repeated f n)
41 (if (= n 0)
42 (lambda (x) x)
43 (compose f (repeated f (- n 1)))))
45 ;; (test-case ((repeated square 2) 5) 625)
46 (test-case (cube-root 5) 1.70997594668)
49 ;; Exercise 1.44. The idea of smoothing a function is an important concept in signal processing. If f is a function and dx is some small number, then the smoothed version of f is the function whose value at a point x is the average of f(x - dx), f(x), and f(x + dx). Write a procedure smooth that takes as input a procedure that computes f and returns a procedure that computes the smoothed f. It is sometimes valuable to repeatedly smooth a function (that is, smooth the smoothed function, and so on) to obtained the n-fold smoothed function. Show how to generate the n-fold smoothed function of any given function using smooth and repeated from exercise 1.43.
51 (define dx 0.01)
53 (define (smooth f)
54 (lambda (x)
55 (/ (+ (f x)
56 (f (+ x dx))
57 (f (- x dx)))
58 3.0)))
59 (define (n-fold-smooth f n)
60 ((repeated smooth n) f))