<< Previous exercise (2.6)
| Index |
Next exercise (2.8) >>
;; ex 2.7
(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)))
(define i (make-interval 2 7))
(define j (make-interval 8 3))
We could create a function to get rid of the brief duplication in upper-bound and lower-bound, but it's not worth it.
The above is what I had as well; Though I think using min/max may not be necessary. If you look at the
passage in the book regarding the add-interval procedure; The passage and the implementation indicate that lower-bound is positional rather than value dependent. At least as long as the make-interval procedure is unchanged.
Alyssa first writes a procedure for adding two intervals. She reasons that the minimum value the sum could be is the sum of the two lower bounds and the maximum value it could be is the sum of the two upper bounds:
(define (add-interval x y)
(make-interval (+ (lower-bound x) (lower-bound y))
(+ (upper-bound x) (upper-bound y))))
So it looks like we could possibly define this as the following and still be within the constraints given by
(define upper-bound cdr)
(define lower-bound car)
I don't agree with Smith. Car and cdr work perfectly fine if the user always puts either upper-bound or lower-bound first, but I think the problem is that the user might put upper-bound first sometimes and put lower-bound first other times. In this case, interval data structure won't work. So I vote for using max and min.