Chapter 2, Building Abstractions with Data
Section - 2.1 - Introduction to Data Abstraction
Exercise 2.1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#lang sicp
(define (make-rat n d)
(define (make-rat-aux n d)
(let (
(g (gcd n d))
)
(cons (/ n g) (/ d g))
)
)
(if (< d 0)
(make-rat-aux (- n) (- d))
(make-rat-aux n d)
)
)
(define (numer x) (car x))
(define (denom x) (cdr x))
(define (print-rat x)
(newline)
(display (numer x))
(display "/")
(display (denom x))
)
(define (gcd a b)
(define (gcd-abs a b)
(if (= b 0)
a
(gcd
b (remainder a b)
)
)
)
(gcd-abs (abs a) (abs b))
)
Note that procedure gcd
is changed to work with negative integers.
Sample output:
1
2
3
4
5
6
7
8
9
10
11
12
> (print-rat (make-rat -10 -40))
1/4
> (print-rat (make-rat 10 -40))
-1/4
> (print-rat (make-rat -10 40))
-1/4
> (print-rat (make-rat 10 40))
1/4