Exercise 2.1 asks us to define a better version of
make-rat that handles both positive and negative arguments. Here's the last version from the text, along with several example cases to show how it works:(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
> (define x (make-rat 1 2))
> (print-rat x)
1/2
> (define x (make-rat -1 -2))
> (print-rat x)
-1/-2
> (define x (make-rat 1 -2))
> (print-rat x)
1/-2
> (define x (make-rat -1 2))
> (print-rat x)
-1/2
The new version of
make-rat should normalize the sign so that if the resulting rational number is positive, both the numerator and denominator are positive. If the rational number is negative, only the numerator should be negative.We can correct
make-rat by checking to see if the denominator is negative. If it is, we need to multiply both the numerator and denominator by -1 to normalize the result. If not, we just pass the arguments bare to cons.(define (make-rat n d)
(let ((g (gcd n d)))
(if (< d 0)
(cons (/ (* n -1) g) (/ (* d -1) g))
(cons (/ n g) (/ d g)))))
We can use the same definitions as before to see the results from the new
make-rat procedure.> (define x (make-rat 1 2))
> (print-rat x)
1/2
> (define x (make-rat -1 -2))
> (print-rat x)
1/2
> (define x (make-rat 1 -2))
> (print-rat x)
-1/2
> (define x (make-rat -1 2))
> (print-rat x)
-1/2
Related:
For links to all of the SICP lecture notes and exercises that I've done so far, see The SICP Challenge.
2 comments:
LISP is one thing I've always wanted to learn. I've seen you around on StackOverflow and noticed you committed to the game of go proposal, which I'd like to thank you for, because I just can't wait until it goes beta. Anyway, these posts about SICP are invaluable. I'll be coming back to visit.
AMB,
I'm really looking forward to the Game of Go site too. I've gotten one other person to join, and he's really active in a Go club so I hope he'll bring others. I haven't played OTB in a couple of years now, so I really need all the help I can get. :)
Post a Comment