乐正

Actions speak louder than words.

Sicp-ex2-2

问题

请考虑平面上线段的表示问题。一个线段用一对点表示,它们分别是线段的始点和终点。请 定义构造函数make-segment和选择函数start-segmentend-segment,它们基于点定 义线段的表示。进而,一个点可以用数的序对表示,序对的两个成分分别表示点的$x$坐标 和$y$坐标。请据此进一步给出构造函数make-point和选择函数x-pointy-point, 用它们定义出点的这种表示。最后,请基于所定义的构造函数,定义出过程midpoint-segment, 它以一个线段为参数,返回线段的中点(也就是坐标值是两个端点的平均值的点)。为了试 验这些过程,还需要定义一种打印点的方法:

print-point过程 (p60-print-point.scm) download
1
2
3
4
5
6
7
(define (print-point p)
  (newline)
  (display "(")
  (display (x-point p))
  (display ",")
  (display (y-point p))
  (display ")"))

解答

练习2.2 (ex2-2.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
(define (make-point x y)
  (cons x y))

(define (x-point p)
  (car p))

(define (y-point p)
  (cdr p))

(define (make-segment x1 y1 x2 y2)
  (cons (make-point x1 y1)
        (make-point x2 y2)))

(define (start-segment segment)
  (car segment))

(define (end-segment segment)
  (cdr segment))

(define (midpoint-segment segment)
  (make-point (average (x-point (start-segment segment))
                       (x-point (end-segment segment)))
              (average (y-point (start-segment segment))
                       (y-point (end-segment segment)))))

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(define s (make-segment 3 4 9 12))
;Value: s

(start-segment s)
;Value 15: (3 . 4)

(end-segment s)
;Value 16: (9 . 12)

(print-point (start-segment s))

(3,4)
;Unspecified return value

(print-point (end-segment s))

(9,12)
;Unspecified return value

(print-point (midpoint-segment s))

(6,8)
;Unspecified return value

draft

« sicp-ex2-1 sicp-ex2-3 »

Comments