SICP - Solution: Exercise 2.1

Nov 5, 2018 06:09 · 122 words · 1 minute read

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

Solution

One solution is:

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

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

; --- Solution ---

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

; --- Tests ---

(print-rat (make-rat  2 -4))
(print-rat (make-rat -2  4))

Which evaluates to:

-1/2
-1/2