Blob


1 ;; Exercise 2.2. Consider the problem of representing line segments in a plane. Each segment is represented as a pair of points: a starting point and an ending point. Define a constructor make-segment and selectors start-segment and end-segment that define the representation of segments in terms of points. Furthermore, a point can be represented as a pair of numbers: the x coordinate and the y coordinate. Accordingly, specify a constructor make-point and selectors x-point and y-point that define this representation. Finally, using your selectors and constructors, define a procedure midpoint-segment that takes a line segment as argument and returns its midpoint (the point whose coordinates are the average of the coordinates of the endpoints). To try your procedures, you'll need a way to print points:
3 (define (make-point x y)
4 (cons x y))
5 (define (x-point p)
6 (car p))
7 (define (y-point p)
8 (cdr p))
10 (define (make-segment start end)
11 (cons start end))
12 (define (start-segment seg)
13 (car seg))
14 (define (end-segment seg)
15 (cdr seg))
16 (define (midpoint-segment seg)
17 (define (average x y)
18 (/ (+ x y) 2))
19 (let ((x1 (x-point (start-segment seg)))
20 (x2 (x-point (end-segment seg)))
21 (y1 (y-point (start-segment seg)))
22 (y2 (y-point (end-segment seg))))
23 (make-point (average x1 x2)
24 (average y1 y2))))
26 (define (print-point p)
27 (newline)
28 (display "(")
29 (display (x-point p))
30 (display ",")
31 (display (y-point p))
32 (display ")"))
34 (define x1y2 (make-point 1 2))
35 (define x-4y-3 (make-point -4 -3))
36 (define x1y2tox-4y-3 (make-segment x1y2 x-4y-3))
37 (print-point (midpoint-segment x1y2tox-4y-3))
38 (display "=(-3/2,-1/2)")
40 ;; Exercise 2.3. Implement a representation for rectangles in a plane. (Hint: You may want to make use of exercise 2.2.) In terms of your constructors and selectors, create procedures that compute the perimeter and the area of a given rectangle. Now implement a different representation for rectangles. Can you design your system with suitable abstraction barriers, so that the same perimeter and area procedures will work using either representation?
42 ;; makes rectangle given 4 points: top-left, top-right, bottom-left, bottom-right
43 ;; (define (make-rect tl tr bl br)
44 ;; (cons (cons tl tr)
45 ;; (cons bl br)))
46 ;; (define (top-left rect)
47 ;; (caar rect))
48 ;; (define (top-right rect)
49 ;; (cdar rect))
50 ;; (define (bot-left rect)
51 ;; (cadr rect))
52 ;; (define (bot-right rect)
53 ;; (cddr rect))
55 ;; makes rectangle given 2 points: top-left and bottom-right
56 (define (make-rect tl br)
57 (let ((tr (make-point (x-point br) (y-point tl)))
58 (bl (make-point (x-point tl) (y-point br))))
59 (cons (cons tl tr)
60 (cons bl br))))
61 (define (top-left rect)
62 (caar rect))
63 (define (bot-right rect)
64 (cddr rect))
65 (define (top-right rect)
66 (cdar rect))
67 (define (bot-left rect)
68 (cadr rect))
72 (define (perimeter rect)