# 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 (mul-rat one-half one-third));1/6

(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))))
```
##### 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()