SICPの2.1.1 Example: Arithmetic Operations for Rational NumbersあたりをPythonでやってみた
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 (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)))) ;;Representing rational numbers (define (make-rat n d) (cons n d)) (define (numer x) (car x)) (define (denom x) (cdr x)) (define (print-rat x) (newline) (display (numer x)) (display "/") (display (denom x))) (define one-half (make-rat 1 2)) (print-rat one-half);1/2 (define one-third (make-rat 1 3)) (print-rat (add-rat one-half one-third));5/6 (print-rat (mul-rat one-half one-third));1/6 (print-rat (add-rat one-third one-third));6/9 (define (make-rat n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (define (gcd a b) ;<-- SICP1.2.5 Greatest Common Divisors (if (= b 0) a (gcd b (remainder a b)))) (print-rat (add-rat one-third one-third));2/3
python
def add_rat(x, y): return make_rat(numer(x) * denom(y) + numer(y) * denom(x), denom(x) * denom(y)) def sub_rat(x, y): return make_rat(numer(x) * denom(y) - numer(y) * denom(x), denom(x) * denom(y)) def mul_rat(x, y): return make_rat(numer(x) * numer(y), denom(x) * denom(y)) def div_rat(x, y): return make_rat(numer(x) * denom(y), denom(x) * numer(y)) def equal_rat(x, y): return numer(x) * denom(y) == denom(x) * numer(y) #Representing rational numbers def make_rat(n, d): return [n,d] def numer(x): return x[0] def denom(x): return x[1] def print_rat(x): return "%d/%d" % (numer(x), denom(x)) def one_half(): return make_rat(1, 2) print print_rat(one_half())#1/2 def one_third(): return make_rat(1, 3) # not one_third but one_third() print print_rat(add_rat(one_half(), one_third()))#5/6 print print_rat(mul_rat(one_half(), one_third()))#1/6 print print_rat(add_rat(one_third(), one_third()))#6/9 def make_rat(n, d): g = gcd(n, d) return [n / g, d / g] def gcd(a, b): if b == 0: return a return gcd(b, a % b) print print_rat(add_rat(one_third(), one_third()))#2/3