SICP Solutions: Sections 2.1.1 and 2.1.2
Chapter 2
Section 2.1 - Introduction to Data Abstraction
Section 2.1.1 - Example: Arithmetic Operations for Rational Numbers
Exercise 2.1
(define (make-rat n d)
(let ((g (abs (gcd n d))))
(cond ((or (and (< n 0) (< d 0))
(and (> n 0) (< d 0)))
(cons (/ (* -1 n) g) (/ (* -1 d) g)))
(else (cons (/ n g) (/ d g))))))
Section 2.1.2 - Abstraction Barriers
Exercise 2.2
(define (make-segment start end) (cons start end))
(define (start-segment segment) (car segment))
(define (end-segment segment) (cdr segment))
(define (make-point x y) (cons x y))
(define (x-point point) (car point))
(define (y-point point) (cdr point))
(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)))))
Exercise 2.3
We assume that the rectangle’s height and width are parallel to the x and y axes to simplify computations. We can define the procedures that calcualte area and perimeter as:
(define (rect-perim rect)
(* 2 (+ (rect-width rect)
(rect-height rect))))
(define (rect-area rect)
(* (rect-width rect)
(rect-height rect)))
Note that these depend only on the rect-width
and rect-height
selectors. Now
we can create a rectangle representation based on its two opposing points:
(define (make-rect a c)
(cons a c))
(define (rect-width rect)
(abs (- (x-point (cdr rect))
(x-point (car rect)))))
(define (rect-height rect)
(abs (- (y-point (cdr rect))
(y-point (car rect)))))
And another representation based on its diagonal. Note that we do not change any of the interfaces, just the underlying implementation:
(define (make-rect a c)
(make-segment a c))
(define (rect-width rect)
(abs (- (x-point (start-segment rect))
(x-point (end-segment rect)))))
(define (rect-height rect)
(abs (- (y-point (start-segment rect))
(y-point (end-segment rect)))))