2.2
练习 2.2 请考虑平面上线段的表示问题。一个线段用一对点表示,它们分别是线段的始点与终点。请定义构造函数 make-segment 和选择函数 start-segment、end-segment,它们基于点定义线段的表示。进而,一个点可以用数的序对表示,序对的两个成分分别表示点的x坐标和y坐标。请据此进一步给出构造函数make-point和选择函数x-point、y-point,用它们定义出点的这种表示。最后,请基于所定义的构造函数和选择函数,定义出过程midpoint-segment,它以一个线段为参数,返回线段的中点(也就是那个坐标值是两个端点的平均值的点)。为了试验这些过程,还需要定义一种打印点的方法:
(define (print-point p)
(newline)
(display "(")
(display (x-point p))
(display ", ")
(display (y-point p))
(display ")"))
(define (make-point x y) (cons x y))
(define (x-point p) (car p))
(define (y-point p) (cdr p))
(define (make-segment start end)
(cons start end)
)
(define (start-segment segment) (car segment))
(define (end-segment segment) (cdr segment))
(define (average x y) (/ (+ x y) 2))
(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)))
)
)
(define (print-point p)
(newline)
(display "(")
(display (x-point p))
(display ", ")
(display (y-point p))
(display ")"))
(define (print-segment segment)
(newline)
(print-point (start-segment segment))
(display " ---- ")
(print-point (end-segment segment))
)
(display "线段:")
(define segment (make-segment (make-point 0 0) (make-point 10 10)))
(print-segment segment)
(newline)
(newline)
(display "线段中点为: ")
(newline)
(print-point (midpoint-segment segment))