Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

ch1

  • Loading branch information...
commit b16f32e78a3c88ca35412963606660d399d2d7b5 1 parent 992affd
@flaming0 authored
Showing with 75 additions and 0 deletions.
  1. +45 −0 ch1/ex1-45.scm
  2. +30 −0 ch1/ex1-46.scm
View
45 ch1/ex1-45.scm
@@ -1,2 +1,47 @@
;; Example 1.45
+(define (compose f g)
+ (lambda (x) (f (g x))))
+
+(define (repeated f n)
+ (if (= n 0) (lambda (x) x)
+ (compose (repeated f (- n 1)) f)))
+
+(define tolerance 0.00001)
+
+(define (close-enough? a b)
+ (< (abs (- a b)) tolerance))
+
+(define (average a b)
+ (/ (+ a b) 2))
+
+(define (average-damp f)
+ (lambda (x) (average x (f x))))
+
+(define (square x)
+ (* x x))
+
+(define (fixed-point f first-guess)
+ (define (try guess)
+ (let ((next (f guess)))
+ (if (close-enough? guess next)
+ next
+ (try next))))
+ (try first-guess))
+
+(define (my-sqrt x)
+ (fixed-point (average-damp (lambda (y) (/ x y)))
+ 1.0))
+
+(my-sqrt 16)
+
+(define (my-4-root x)
+ (fixed-point (repeated (average-damp
+ (lambda (y)
+ (/ x (* y y y))))
+ 2)
+ 1.0))
+
+(my-4-root 4096)
+
+;; Full procedure
View
30 ch1/ex1-46.scm
@@ -1,2 +1,32 @@
;; Example 1.46
+(define (iterative-improve good? improve)
+ (lambda (first)
+ (define (try guess)
+ (let ((next (improve guess)))
+ (if (good? guess next)
+ next
+ (try next))))
+ (try first)))
+
+(define tolerance 0.0001)
+
+(define (average a b)
+ (/ (+ a b) 2.0))
+
+(define (average-damp f)
+ (lambda (x) (average x (f x))))
+
+(define (my-sqrt n)
+ ((iterative-improve
+ (lambda (guess next) (< (abs (- guess next)) tolerance))
+ (average-damp (lambda (y) (/ n y))))
+ 1.0))
+
+(my-sqrt 4.0)
+
+(define (fixed-point f first)
+ ((iterative-improve
+ (lambda (guess next) (< (abs (- guess next)) tolerance))
+ f)
+ first))
Please sign in to comment.
Something went wrong with that request. Please try again.