Blame


1 665c255d 2023-08-04 jrmu ;; 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:
2 665c255d 2023-08-04 jrmu
3 665c255d 2023-08-04 jrmu (define (make-point x y)
4 665c255d 2023-08-04 jrmu (cons x y))
5 665c255d 2023-08-04 jrmu (define (x-point p)
6 665c255d 2023-08-04 jrmu (car p))
7 665c255d 2023-08-04 jrmu (define (y-point p)
8 665c255d 2023-08-04 jrmu (cdr p))
9 665c255d 2023-08-04 jrmu
10 665c255d 2023-08-04 jrmu (define (make-segment start end)
11 665c255d 2023-08-04 jrmu (cons start end))
12 665c255d 2023-08-04 jrmu (define (start-segment seg)
13 665c255d 2023-08-04 jrmu (car seg))
14 665c255d 2023-08-04 jrmu (define (end-segment seg)
15 665c255d 2023-08-04 jrmu (cdr seg))
16 665c255d 2023-08-04 jrmu (define (midpoint-segment seg)
17 665c255d 2023-08-04 jrmu (define (average x y)
18 665c255d 2023-08-04 jrmu (/ (+ x y) 2))
19 665c255d 2023-08-04 jrmu (let ((x1 (x-point (start-segment seg)))
20 665c255d 2023-08-04 jrmu (x2 (x-point (end-segment seg)))
21 665c255d 2023-08-04 jrmu (y1 (y-point (start-segment seg)))
22 665c255d 2023-08-04 jrmu (y2 (y-point (end-segment seg))))
23 665c255d 2023-08-04 jrmu (make-point (average x1 x2)
24 665c255d 2023-08-04 jrmu (average y1 y2))))
25 665c255d 2023-08-04 jrmu
26 665c255d 2023-08-04 jrmu (define (print-point p)
27 665c255d 2023-08-04 jrmu (newline)
28 665c255d 2023-08-04 jrmu (display "(")
29 665c255d 2023-08-04 jrmu (display (x-point p))
30 665c255d 2023-08-04 jrmu (display ",")
31 665c255d 2023-08-04 jrmu (display (y-point p))
32 665c255d 2023-08-04 jrmu (display ")"))
33 665c255d 2023-08-04 jrmu
34 665c255d 2023-08-04 jrmu (define x1y2 (make-point 1 2))
35 665c255d 2023-08-04 jrmu (define x-4y-3 (make-point -4 -3))
36 665c255d 2023-08-04 jrmu (define x1y2tox-4y-3 (make-segment x1y2 x-4y-3))
37 665c255d 2023-08-04 jrmu (print-point (midpoint-segment x1y2tox-4y-3))
38 665c255d 2023-08-04 jrmu (display "=(-3/2,-1/2)")