Chapter 2, Building Abstractions with Data

Section - 2.1 - Introduction to Data Abstraction

Exercise 2.12


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#lang sicp

(#%require (only racket/base error))

(define (make-center-percent c p)
  (let ((width (/ (* c p) 100)))
    (make-interval (- c width) (+ c width))
  )
)

(define (percent-tolerance x) 
   (let (
           (center (/ (+ (upper-bound x) (lower-bound x)) 2.0)) 
           (width (/ (- (upper-bound x) (lower-bound x)) 2.0))
        ) 
        (* (/ width center) 100)
   )
)

(define (make-center-width c w)
  (make-interval (- c w) (+ c w)))
(define (center i)
  (/ (+ (lower-bound i) (upper-bound i)) 2))
(define (width i)
  (/ (- (upper-bound i) (lower-bound i)) 2))
  
(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 intvl (make-center-percent 100 10))
> (display-interval intvl)
[90,110]
> (percent-tolerance intvl)
10.0
> (define intvl (make-center-percent 500 15))
> (display-interval intvl)
[425,575]