SICP 2.1 exercises

Was busy today with real work, but I managed to squeeze in an hour or so.


(define (make-rat n d)
  (let ((g (abs (gcd n d))))
    (if (< d 0)
        (cons (/ (* -1 n) g) (/ (* -1 d) g))
        (cons (/ n g) (/ d g)))))

I was impatient with this one and got the answer from here. However, just that doesn’t work because the gcd given in the previous chapter cannot deal with negatives, hence the additional absolute value operator.


(define (make-segment p1 p2)
  (cons p1 p2))

(define (start-segment segment)
  (car segment))

(define (end-segment segment)
  (cdr segment))

(define (make-point x y)
  (cons x y))

(define (x-point p)
  (car p))

(define (y-point p)
  (cdr p))

(define (midpoint-segment line-segment)
  (make-point (/ (+ (x-point (start-segment line-segment))
                    (x-point (end-segment line-segment)))
              (/ (+ (y-point (start-segment line-segment))
                    (y-point (end-segment line-segment)))

Straightforward implementation again. It would probably have been better to abstract out some things, but I decided to work with messy scheme code to get used to it.


(define (rectangle-1 top-left bottom-right)
  (cons top-left bottom-right))

(define (top-left-1 rectangle)
  (car rectangle))

(define (bottom-right-1 rectangle)
  (cdr rectangle))

(define (rectangle-2 top-left w h)
  (cons top-left (cons w h)))

(define (top-left-2 rectangle)
  (car rectangle))

(define (bottom-right-2 rectangle)
  (make-point (+ (x-point (car rectangle)) (car (cdr rectangle)))
              (+ (y-point (car rectangle)) (cdr (cdr rectangle)))))

(define (area rectangle)
  (* (abs (- (x-point (top-left rectangle))
             (x-point (bottom-right rectangle))))
     (abs (- (y-point (top-left rectangle))
             (y-point (bottom-right rectangle))))))

Not too hard again. In order to test I ran something like (define top-left top-left-1) within the interpreter.


Just work through the substitution…

(car (cons x y))
(car (lambda (m) (m x y)))
((lambda (m) (m x y)) (lambda (p q) p))
((lambda (x y) x))

Clearly the corresponding cdr is just to return q instead of p.

(define (cdr z)
  (z (lambda (p q) q)))

Comments: Again pretty easy as expected from introductory exercises.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s