Implement 2.1
This commit is contained in:
parent
32b723deee
commit
1a8a806f35
55
ex-2_01-xx.scm
Normal file
55
ex-2_01-xx.scm
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
(load "util.scm")
|
||||||
|
|
||||||
|
(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))
|
||||||
|
(* (numer y) (denom x))))
|
||||||
|
|
||||||
|
(define (make-rat n d)
|
||||||
|
(let ((g (gcd n d)))
|
||||||
|
(cons (/ n g) (/ d g))))
|
||||||
|
(define (numer x) (car x))
|
||||||
|
(define (denom x) (cdr x))
|
||||||
|
|
||||||
|
(define (print-rat x)
|
||||||
|
(newline)
|
||||||
|
(display (numer x))
|
||||||
|
(display "/")
|
||||||
|
(display (denom x)))
|
||||||
|
|
||||||
|
; Examples
|
||||||
|
; (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))
|
||||||
|
|
||||||
|
(display "ex-2.1")
|
||||||
|
|
||||||
|
(define (make-rat n d)
|
||||||
|
(let ((g (gcd n d)))
|
||||||
|
(if (< (* n d) 0)
|
||||||
|
(cons (- (abs (/ n g))) (abs (/ d g)))
|
||||||
|
(cons (abs (/ n g)) (abs (/ d g))))))
|
||||||
|
|
||||||
|
(print-rat (make-rat 3 9))
|
||||||
|
(print-rat (make-rat -3 9))
|
||||||
|
(print-rat (make-rat 3 -9))
|
||||||
|
(print-rat (make-rat -3 -9))
|
||||||
|
|
||||||
|
(display "\n\nex-2.2")
|
||||||
|
|
Loading…
Reference in New Issue
Block a user