SICP Exercise 2.1

Question

Define a better version of make-rat that handles both positive and negative arguments. Make-rat should normalise the sign so that if the rational number is positive, both the numerator and the denominator are positive, and if the rational number is negative, only the numerator is negative.

Answer

(define (gcd a b)
  (if (= b 0)
      a
      (gcd b (remainder a b))))

(define (make-rat n d)
  (let ((positive-n? (> n 0))
        (positive-d? (> d 0))
        (g (gcd (abs n) (abs d))))
    (cons ((if (equal? positive-n? positive-d?) + -) (/ (abs n) g)) (/ (abs d) g))))

(define (numer x) (car x))
(define (denom x) (cdr x))

(define (print-rat x)
  (display (numer x))
  (display "/")
  (display (denom x))
  (newline))

(define a (make-rat 1 3))
(define b (make-rat -4 6))
(define c (make-rat 3 -9))
(define d (make-rat -9 -12))

(print-rat a)
(print-rat b)
(print-rat c)
(print-rat d)

Results:

1/3
-2/3
-1/3
3/4