-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.1.rkt
More file actions
53 lines (43 loc) · 1.17 KB
/
2.1.rkt
File metadata and controls
53 lines (43 loc) · 1.17 KB
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
#lang racket
(define (make-rat n d)
(let ((g (gcd n d)))
(sign-clean (/ n g) (/ d g))))
(define (sign-clean n d)
(cons (if (>= d 0) n (- n))
(abs d)))
(define (numer x) (car x))
(define (denom x) {cdr x})
(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 (div-rat x y)
(make-rat (* (numer x) (denom y))
(* (denom x) (numer y))))
(define (equal-rat? x y)
(= (* (numer x) (* denom y))
(* (denom x) (numer y))))
(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))))
;test
(define one-half (make-rat 1 2))
(print-rat one-half)
(define one-third (make-rat 1 3))
(print-rat (add-rat one-half one-third))
(print-rat (mul-rat one-half one-third))
(print-rat (add-rat one-third one-third))
(print-rat (make-rat 3 -9))