Note: this wiki is now retired and will no longer be updated!
The static final versions of the pages are left as a convenience for readers. Note that meta-pages such as "discussion," "history," etc., will not work.
SICP exercise 2.02
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:
(define (print-point p) (newline) (display "(") (display (x-point p)) (display ",") (display (y-point p)) (display ")"))
Points are pairs of numbers, and segments are pairs of points.
(define (make-point x y) (cons x y)) (define (x-point p) (car p)) (define (y-point p) (cdr p)) (define (make-segment p1 p2) (cons p1 p2)) (define (start-segment p) (car p)) (define (end-segment p) (cdr p))
Here's the midpoint-segment procedure:
(define (average x y) (/ (+ x y) 2)) (define (midpoint-segment s) (let ((midx (average (x-point (start-segment s)) (x-point (end-segment s)))) (midy (average (y-point (start-segment s)) (y-point (end-segment s))))) (make-point midx midy)))
(print-point (make-point 0 0))
(print-point (make-point 3 2))
(define p1 (make-point 1 2)) (print-point p1)
(define p2 (make-point 5 2)) (print-point p2)
(define s1 (make-segment p1 p2)) (print-point (midpoint-segment s1))
(define p3 (make-point 0 0)) (define p4 (make-point 5 4)) (define s2 (make-segment p3 p4)) (print-point (midpoint-segment s2))