-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsol-2.3.tex
54 lines (46 loc) · 1.46 KB
/
sol-2.3.tex
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Let's assume for simplicity that we want to represent only rectangles with horizontal and vertical sides.
Here are two ways we can use to represent such a rectangle:
\begitems\style n
* We can describe it simply by giving one of its diagonals (a segment of exercise~\ref[2.2]).
Constructor:
\begtt\scm
(define (make-rectangle diagonal)
diagonal)
\endtt
Some selectors:
\begtt\scm
(define (base r)
(abs (- (x-point (start-segment r))
(x-point (end-segment r)))))
(define (height r)
(abs (- (y-point (start-segment r))
(y-point (end-segment r)))))
\endtt
* Alternatively, we can describe it by giving its upper-left vertex (a point of exercise~\ref[2.2]) and the lengths of its sides (positive numbers).
\smallskip
Constructor:
\begtt\scm
(define (make-rectangle upper-left-vertex base height)
(cons upper-left-vertex
(cons base height)))
\endtt
Some selectors:
\begtt\scm
(define (base r)
(car (cdr r)))
(define (height r)
(cdr (cdr r)))
\endtt
\enditems
\begtt\scm
\endtt
For both representations of a rectangle we defined the selectors `base` and `height` that give respectively the length of the horizontal and vertical sides of the rectangle.
These selectors are abstraction barriers that allow us to define the procedures for computing the perimeter and area of any rectangle, without knowing its representation:
\begtt\scm
(define (perimeter r)
(* 2 (+ (base r)
(height r))))
(define (area r)
(* (base r)
(height r)))
\endtt