Alyssa's program is incomplete because she has not specified the implementation of the interval abstraction. Here is a definition of the interval constructor:
(define (make-interval a b) (cons a b))
Define selectors
upper-bound
and lower-bound
to complete the implementation. A nice and straightforward exercise. We have two values held in a pair. The upper-bound will be the maximum of the two values; the lower-bound will be the minimum of the two. I've already noted that Scheme has a couple of predefined procedures,
max
and min
that can make this determination for us, so the implementations are simply:
(define (upper-bound i) (max (car i) (cdr i))) (define (lower-bound i) (min (car i) (cdr i)))And a quick test:
> (define i1 (make-interval 5 10)) > (define i2 (make-interval 7 2)) > (lower-bound i1) 5 > (upper-bound i1) 10 > (lower-bound i2) 2 > (upper-bound i2) 7
This comment has been removed by the author.
ReplyDelete