Chapter 2, Building Abstractions with Data
Section - 2.1 - Introduction to Data Abstraction
Exercise 2.8
Alyssa initializes lower-bound with the minum possible value lower-bound can get while carrying put the corresponding arithmetic operation.
Thus we can extend the same to write sub-interval
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#lang sicp
(define (sub-interval x y)
(make-interval (- (lower-bound x) (upper-bound y))
(- (upper-bound x) (lower-bound y)))
)
(define (make-interval a b) (cons a b))
(define (lower-bound x) (min (car x) (cdr x)))
(define (upper-bound x) (max (car x) (cdr x)))
(define (display-interval x)
(display "[")
(display (lower-bound x))
(display ",")
(display (upper-bound x))
(display "]")
(newline)
)
Output:
1
2
3
4
5
6
7
8
> (define intrvl (make-interval -50 -100))
> (display-interval intrvl)
[-100,-50]
> (define intrvl2 (make-interval -10 -40))
> (display-interval intrvl2)
[-40,-10]
> (display-interval (sub-interval intrvl intrvl2))
[-90,-10]