Pages

Friday, April 22, 2011

Exercises 1.40 - 1.44

These were exercises on writing procedures which return procedures. They went pretty quick, and I don't have a lot to write up for them. I have sample output that verifies the solution for most of them.

Exercise 1.40 Define a procedure cubic to approximate zeros of the cubic x3 + ax2 + bx + c.

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


Exercise 1.41 Define a procedure double that takes a procedure of one argument as argument and returns a procedure that applies the original procedure twice.

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

((double square) 2)
;Value: 16

(((double (double double)) inc) 5)
;Value: 21

Exercise 1.42 Define a procedure compose that implements composition.

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

((compose square inc) 6)
;Value: 49

Exercise 1.43 Write a procedure that takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f.

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

((repeated square 2) 5)
;Value: 625

Exercise 1.44 Write a procedure smooth that takes as input a procedure that computes f and returns a procedure that computes the smoothed f.

(define (smooth f)
  (lambda (x)
    (let ((dx .00001))
      (/ (+ (f (+ x dx)) (f x) (f (- x dx))) 3.0))))

(sqrt 4)
;Value: 2.0000000944796694

(((repeated smooth 10) sqrt) 4)
;Value: 2.0000000944692538


I'm not sure whether sqrt doesn't respond to smoothing, the dx is too large, or this solution isn't right. But I think it's right.