# weima learns to program

my attempt to do the exercises in sicp.

## Sunday, July 6, 2008

### sicp exercise 2.2

; 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:

(begin
(define (print-segment s)
(display "(")
(print-point (start-point s))
(display ",")
(print-point (end-point s))
(display ")")
)
(define (print-point p)
(display "(")
(display (x-point p))
(display ",")
(display (y-point p))
(display ")")
)
(define make-segment (lambda (start end )(cons start end)))
(define start-point (lambda (segment) (car segment)))
(define end-point   (lambda (segment) (cdr segment)))
(define make-point  (lambda (x y) ( cons x y)))
(define x-point   (lambda (p) ( car p )))
(define y-point   (lambda (p) ( cdr p )))
(define middle    (lambda (x y) (/ (+  x y) 2)))
(define midpoint-segment (lambda (segment)
(make-point
(middle (x-point (start-point segment)) (x-point (end-point segment)))
(middle (y-point (start-point segment)) (y-point (end-point segment))))))

(print-segment (make-segment (make-point 2 3) (make-point 5 6)))
(newline)
(print-point (midpoint-segment ( make-segment (make-point 2 3) (make-point 5 6))))
(newline)
)