# sicp-ex-2.1

```
;; ex 2.1

(define (numer x) (car x))

(define (denom x) (cdr x))

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

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

;; Testing
(print-rat (make-rat 6 9)) ; 2/3
(print-rat (make-rat -6 9)) ; -2/3
(print-rat (make-rat 6 -9)) ; -2/3
(print-rat (make-rat -6 -9)) ; 2/3

```

There is a bug in the solution above. If gcd is defined as described in 1.2.5, it will have sign depending on the number of iterations it runs and the signs of a and b. For example:

```(gcd 1 -2) ; 1
(gcd 6 -9) ; -3
```

Thus:

```(print-rat (make-rat 1 -2)) ; 1/-2
(print-rat (make-rat 6 -9)) ; -2/3
```

To fix either make gcd return an absolute value or get the absolute value in make-rat (this is implemented below):

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

If we don't want to consider the sign of gcd, and still get the right answer, we could implement the following:

```(define (make-rat n d)
(define g (gcd n d))
(cond ((> (* n d) 0) (cons (abs (/ n g)) (abs (/ d g))))
((< (* n d) 0) (cons (- (abs (/ n g))) (abs (/ d g))))))
```

Lily X. :)

We could save the simplified numbers as variables to make the program more readable too

``` (define (make-rat n d)
(define g (gcd n d))
(let        ((simple-n (abs (/ n g)))
(simple-d (abs (/ d g))))
(cond
((> (* n d) 0) (cons simple-n simple-d))
((< (* n d) 0) (cons (- simple-n) simple-d)))))
```