Exercise 2.3 of SICP

Exercise 2.3: Implement a representation for rectangles in a plane. (Hint: You may want to make use of exercise 2.2.) In terms of your constructors and selectors, create procedures that compute the perimeter and the area of a given rectangle. Now implement a different representation for rectangles. Can you design your system with suitable abstraction barriers, so that the same perimeter and area procedures will work using either representation? I have decided to use a diagonal segment for representation of make-rectangle and a point with both dimensional magnitudes for make-rectangle2.

(define (make-segment p1 p2)
(cons p1 p2))
(define (start-segment s)
(car s))
(define (end-segment s)
(cdr s))
(define (average a b) (/ (+ a b) 2.0))
(define (make-point x y)
(cons x y))
(define (x-point p)
(car p))
(define (y-point p)
(cdr p))
(define (midpoint-segment s)
(make-point
(average
(x-point (start-segment s))
(x-point (end-segment s)))
(average
(y-point (start-segment s))
(y-point (end-segment s)))))

(define (dimension direction r)
(- (direction (end-segment r))
(direction (start-segment r))))

(define (width r) (dimension y-point r))
(define (length r) (dimension x-point r))

(define (make-rectangle s) s)

(define (make-rectangle2 p length width)
(make-segment p
(make-point
(+ (x-point p) length)
(+ (y-point p) width))))

(define (area r)
(* (length r)
(width r)))

(define (perimeter r)
(* 2 (+ (length r)
(width r))))

(define R
(make-rectangle (make-segment
(make-point 0 0)
(make-point 4 4))))

> (area R)
16
> (perimeter R)
16

(define R2 (make-rectangle2
(make-point 0 0)
4 4))

> (area R2)
16
> (perimeter R2)
16

(define R
(make-rectangle (make-segment
(make-point 2 1)
(make-point 5 4))))

> (area R)
9
> (perimeter R)
12

(define R2 (make-rectangle2
(make-point 2 1)
3 3))

> (area R)
9
> (perimeter R)
12