[ create a new paste ] login | about

Project: programmingpraxis
Link: http://programmingpraxis.codepad.org/ybDFmyJa    [ raw code | output | fork ]

programmingpraxis - Scheme, pasted on Jan 7:
; rational numbers

(define (frac n d)
  (if (zero? d) (error 'frac "can't have zero denominator")
    (if (negative? d) (frac (- n) (- d))
      (let ((g (gcd n d)))
        (if (= g 1) (cons n d)
          (cons (/ n g) (/ d g)))))))

(define (plus x y)
  (let ((a (car x)) (b (cdr x)) (c (car y)) (d (cdr y)))
    (frac (+ (* a d) (* b c)) (* b d))))

(define (minus x y)
  (let ((a (car x)) (b (cdr x)) (c (car y)) (d (cdr y)))
    (frac (- (* a d) (* b c)) (* b d))))

(define (times x y)
  (let ((a (car x)) (b (cdr x)) (c (car y)) (d (cdr y)))
    (frac (* a b) (* c d))))

(define (divide x y)
  (let ((a (car x)) (b (cdr x)) (c (car y)) (d (cdr y)))
    (frac (* a d) (* b c))))

(define (less-than? x y)
  (let ((a (car x)) (b (cdr x)) (c (car y)) (d (cdr y)))
    (< (* a d) (* b c))))

(display (plus (frac 1 3) (frac -1 7))) (newline)
(display (minus (frac 1 3) (frac -1 7))) (newline)
(display (times (frac 1 3) (frac -1 7))) (newline)
(display (divide (frac 1 3) (frac -1 7))) (newline)
(display (less-than? (frac 1 3) (frac -1 7))) (newline)


Output:
1
2
3
4
5
(4 . 21)
(10 . 21)
(-3 . 7)
(-7 . 3)
#f


Create a new paste based on this one


Comments: