my attempt to do the exercises in sicp.

Tuesday, July 8, 2008

sicp exercise 2.8


; Exercise 2.8.  Using reasoning analogous to Alyssa's, describe how the difference of two intervals may be computed. Define a corresponding subtraction procedure, called sub-interval.


(define (make-interval a b) (cons a b))
(define (upper-bound interval) (car interval))
(define (lower-bound interval) (cdr interval))

(define (sub-interval x y)
  (let ((max-upper  (max (upper-bound x) (upper-bound y)))
        (min-upper  (min (upper-bound x) (upper-bound y)))
        (max-lower  (max (lower-bound x) (lower-bound y)))
        (min-lower  (min (lower-bound x) (lower-bound y))))
  (make-interval (abs (- max-upper min-lower)) (abs (- min-upper max-lower)))))

(define int1 (make-interval 30 20))
(define int2 (make-interval 100 80))

(display (sub-interval int2 int1)) (newline)

No comments: