1.3.4

Posted on 2015-02-16 00:39:53 +0900 in SICP Lisp

In general, programming languages impose restrictions on the ways in which computational elements can be manipulated. Elements with the fewest restrictions are said to have first-class status. Some of the ``rights and privileges’’ of first-class elements are:

  • They may be named by variables.
  • They may be passed as arguments to procedures.
  • They may be returned as the results of procedures.
  • They may be included in data structures.

1.40

(define tolerance 0.00001)
(define (fixed-point f first-guess)
  (define (close-enough? v1 v2)
    (< (abs (- v1 v2)) tolerance))
  (define (try guess)
    (let ((next (f guess)))
      (if (close-enough? guess next)
          next
          (try next))))
  (try first-guess))

(define dx 0.00001)
(define (deriv g)
  (lambda (x)
    (/ (- (g (+ x dx)) (g x))
       dx)))

(define (newton-transform g)
  (lambda (x)
    (- x (/ (g x) ((deriv g) x)))))

(define (newtons-method g guess)
  (fixed-point (newton-transform g) guess))

(define (square x) (* x x))

(define (cube x) (* x x x))

(define (cubic a b c)
  (lambda (x)
    (+ (cube x)
       (* a (square x))
       (* b x)
       c)))

-> (newtons-method (cubic 8 16 10) 1)
-5.3652300134140924

1.41

(define (double f)
  (lambda (x) (f (f x))))

(define (inc x) (+ x 1))

-> ((double inc) 1)
3

-> (((double (double double)) inc) 5)
21

It increases $2^2^2$.

1.42

(define (compose f g)
 (lambda (x) (f (g x))))

1.43

(define (repeated f x)
  (if (= x 1)
      f
      (compose f (repeated f (- x 1)))))

1.44

(define (smooth f dx)
  (lambda (x)
    (/ (+ (f x)
          (f (+ x dx))
          (f (- x dx)))
       3)))

(define (n-fold-smooth f dx n)
  (repeated (smooth f dx) n))

1.46

(define (iterative-improve good-enough? improve)
   (define (iter guess)
     (if (good-enough? guess)
         guess
         (iter (improve guess))))
   iter)
----------------------------------- 本文内容遵从CC版权协议转载请注明出自kamelzcs -----------------------------------
«  | SICP 1.3.2-1.3.3 »

Hide Comments

comments powered by Disqus