60 likes | 214 Views
(define <rat> <pair>) (define (make-rat <function>) (method ((n <integer>) (d <integer>)) (if (= d 0) (begin (print "zero denominator") (pair 0 1)) (pair n d)))) (define (numer <function>) head) (define (denom <function>) tail) Why not
E N D
(define <rat> <pair>) (define (make-rat <function>) (method ((n <integer>) (d <integer>)) (if (= d 0) (begin (print "zero denominator") (pair 0 1)) (pair n d)))) (define (numer <function>) head) (define (denom <function>) tail) Why not (define (make-rat <function>) pair) ?
(define rat-add (method ((r1 <rat>) (r2 <rat>)) (bind ((n1 (numer r1)) (d1 (denom r1)) (n2 (numer r2)) (d2 (denom r2))) (make-rat (+ (* n1 d2) (* n2 d1)) (* d1 d2))))) (define rat-mul (method ((r1 <rat>) (r2 <rat>)) (bind ((n1 (numer r1)) (d1 (denom r1)) (n2 (numer r2)) (d2 (denom r2))) (make-rat (* n1 n2) (* d1 d2)))))
(define rat-eq (method ((r1 <rat>) (r2 <rat>)) (bind ((n1 (numer r1)) (d1 (denom r1)) (n2 (numer r2)) (d2 (denom r2))) (= (* n1 d2) (* n2 d1))))) (define rat-leq (method ((r1 <rat>) (r2 <rat>)) (bind ((n1 (numer r1)) (d1 (denom r1)) (n2 (numer r2)) (d2 (denom r2))) (if (>= (* d1 d2) 0) ;;if d1 and d2 have same sign (<= (* n1 d2) (* n2 d1)) (>= (* n1 d2) (* n2 d1))))))
(rat-eq (make-rat 10 8) (make-rat 5 4)) => #t This is correct, since 10/8 = 5/4 But (numer (make-rat 10 8)) => 10 (denom (make-rat 10 8)) => 8 (numer (make-rat 5 4)) => 5 (denom (make-rat 5 4)) => 4 What if I wanted lowest term representation?
(define (make-rat <function>) (method ((n <integer>) (d <integer>)) (if (= d 0) (begin (print "zero denominator") (pair 0 1)) (bind ((g (gcd n d))) (pair (/ n g) (/ d g)))))) Now we have representation in lowest terms: (numer (make-rat 10 8)) => 5 (denom (make-rat 10 8)) => 4 so we can simplify equality testing if we want (or not, if we don’t want): (define rat-eq (method ((r1 <rat>) (r2 <rat>)) (and (= (numer r1) (numer r2)) (= (denom r1) (denom r2)))))
(define (make-rat <function>) (method ((n <integer>) (d <integer>)) (if (= d 0) (begin (print "zero denominator") (pair 0 1)) (bind ((n (if (> d 0) n (- n))) (d (if (> d 0) d (- d))) (g (gcd n d))) (pair (/ n g) (/ d g)))))) Now we can simplify testing if we want: (define rat-leq (method ((r1 <rat>) (r2 <rat>)) (bind ((n1 (numer r1)) (d1 (denom r1)) (n2 (numer r2)) (d2 (denom r2))) (<= (* n1 d2) (* n2 d1)))))