-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex2-1.scm
69 lines (54 loc) · 1.22 KB
/
ex2-1.scm
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#lang scheme
(define (add-rat x y)
(make-rat (+ (*
(numer x)
(denom y))
(*
(numer y)
(denom x)))
(*
(denom x)
(denom y))))
(define (sub-rat x y)
(make-rat (- (*
(numer x)
(denom y))
(*
(numer y)
(denom x)))
(*
(denom x)
(denom y))))
(define (mul-rat x y)
(make-rat (*
(numer x)
(numer y))
(*
(denom x)
(denom y))))
(define (divide-rat x y)
(make-rat
(* (numer x)
(denom y))
(* (denom y)
(numer y))))
(define (make-rat x y)
(let ((gcd (gcd x y)))
(cond
((and (negative? x) (negative? y)) (cons (* x -1) (* y -1)))
((negative? x) (cons x y))
((negative? y) (cons (* x -1) (* y -1)))
(else (cons x y)))))
(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)
(if (= b 0)
a
(gcd b (remainder a b))))