sicp-ex-2.8



<< Previous exercise (2.7) | Index | Next exercise (2.9) >>


jz

  
 ;; ex 2.8 
  
 ;; The max and min can be supplied to the constructor in any order. 
 (define (make-interval a b) (cons a b)) 
 (define (upper-bound interval) (max (car interval) (cdr interval))) 
 (define (lower-bound interval) (min (car interval) (cdr interval))) 
  
 ;; The minimum value would be the smallest possible value 
 ;; of the first minus the largest of the second.  The maximum would be 
 ;; the largest of the first minus the smallest of the second. 
 (define (sub-interval x y) 
   (make-interval (- (lower-bound x) (upper-bound y)) 
                  (- (upper-bound x) (lower-bound y)))) 
  
 (define (display-interval i) 
   (newline) 
   (display "[") 
   (display (lower-bound i)) 
   (display ",") 
   (display (upper-bound i)) 
   (display "]")) 
  
 ;; Usage 
 (define i (make-interval 2 7)) 
 (define j (make-interval 8 3)) 
  
 (display-interval i) 
 (display-interval (sub-interval i j)) 
 (display-interval (sub-interval j i)) 
  

shyam

Specifying subtraction in terms of addition is more accurate.

We also have the example of division specified in terms of multiplication in the text

 (define (sub-interval x y) 
   (add-interval x (make-interval (- (upper-bound y)) (- (lower-bound y))))) 

Where add-interval as given in the text is :

 (define (add-interval x y) 
   (make-interval (+ (lower-bound x) (lower-bound y)) 
                  (+ (upper-bound x) (upper-bound y)))) 

This even works for negative valued interval, whether or not , we want to use values in that range ;-)

Here are some examples:

1 ]=> (sub-interval (make-interval 4 5) (make-interval 1 2))

;Value 27: (2 . 4)

1 ]=> (sub-interval (make-interval (- 4) (- 5)) (make-interval 1 2))

;Value 28: (-7 . -5)

1 ]=> (sub-interval (make-interval 4 5) (make-interval (- 1) 2))

;Value 29: (2 . 6)

1 ]=> (sub-interval (make-interval 4 5) (make-interval 1 (- 2)))

;Value 30: (3 . 7)

1 ]=> (sub-interval (make-interval (- 4) 5) (make-interval 1 2))

;Value 31: (-6 . 4)

1 ]=> (sub-interval (make-interval 4 (- 5)) (make-interval 1 2))

;Value 32: (-7 . 3)

1 ]=> 

> This even works for negative valued interval, whether or not , we want to use values in that range ;-)

The proposed solution works for negative values as well. The minimum of two intervals is always (- (lower a) (upper b)), and the maximum is always (- (upper a) (lower b)).

Otherwise, though, you are correct; it certainly is more elegant to define subtraction in terms of addition.