SICP 問題2.2

2017-09-04

平面上の線分を表現する問題を考えよう.
各線分は一対の点: 始発点と終着点で表現されている.
点を使って線分の表現を定義する構成子 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 ")"))

書いた。

;; point method
(define (make-point x y) (cons x y))
(define (x-point p) (car p))
(define (y-point p) (cdr p))
(define (mid-point a b)
  (if (or (and (>= a 0) (>= b 0)) (and (< a 0) (< b 0)))
      (/ (+ a b) 2)
      (+ a b)))
(define (print-point p)
  (display "(")
  (display (x-point p))
  (display ",")
  (display (y-point p))
  (display ")")
  (newline))

;; segment method
(define (make-segment start-point end-point) (cons start-point end-point))
(define (start-segment segment) (car segment))
(define (end-segment segment) (cdr segment))
(define (midpoint-segment segment)
  (let ((start-point (start-segment segment)) (end-point (end-segment segment)))
        (cons
          (mid-point (x-point start-point) (x-point end-point))
          (mid-point (y-point start-point) (y-point end-point)))))


;; test
(define start (make-point -1 -4))
(define end (make-point 3 1))
(print-point start)
; (-1,-4)
(print-point end)
; (3,1)

(define seg (make-segment start end))
(print-point (midpoint-segment seg))
; (2,-3)

(newline)
(define start1 (make-point 0 0))
(define end1 (make-point 4 5))
(print-point start1)
; (0,0)
(print-point end1)
; (4,5)

(define seg1 (make-segment start1 end1))
(print-point (midpoint-segment seg1))
; (2,5/2)

答えをみたら、負の値は考慮してないっぽかった。