Programming to an interface via constructors, selectors, and the closure property
$$ \frac{1}{3} + \frac{1}{6} = \frac{1}{2} $$
make_rat($n$, $d$)numer($r$), denom($r$)add_rat, mul_rat, equal_ratr[0])$$ \frac{n_1}{d_1}+\frac{n_2}{d_2}=\frac{n_1 d_2+n_2 d_1}{d_1 d_2} $$
def add_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 equal_rat(x, y):
return numer(x) * denom(y) == numer(y) * denom(x)add_rat($x$, $y$)add_rat, mul_rat, ...)make_rat, numer, denommak$e_r$atfrom math import gcddef make_rat(n, d):
if d == 0:
raise ZeroDivisionError("denominator cannot be 0")g = gcd(n, d)
n //= g
d //= g# Normalize sign: denominator always positive
if d < 0:
n, d = -n, -dadd_rat improves automaticallydef pair(x, y):
def dispatch(m):
if m == 0:
return x
elif m == 1:
return y
raise ValueError("m must be 0 or 1")return dispatchdef first(p):
return p(0)def second(p):
return p(1)first(pair($x$, $y$)) is $x$def make_point(x, y):
return (x, y)def x_coord(p):
return p[0]def y_coord(p):
return p[1]def make_segment(p1, p2):
return (p1, p2)p[0] inside geometry codesub_rat($x$, $y$) using only make_rat, numer, denomr[0]?
Powered by SciMigo AI Tutor - https://scimigo.com