Skip to content

Instantly share code, notes, and snippets.

@faiface
Created January 19, 2019 17:34
Show Gist options
  • Save faiface/df39634a7646640f1fa27bef6d56bfbb to your computer and use it in GitHub Desktop.
Save faiface/df39634a7646640f1fa27bef6d56bfbb to your computer and use it in GitHub Desktop.
record Rat =
nom : Int,
den : Int,
func gcd : Int -> Int -> Int =
\a \b
if (zero? b) a;
gcd b (a % b)
func norm : Rat -> Rat =
\x
let (gcd (abs; nom x) (abs; den x)) \d
if (d == 0) x;
if (den x < 0) (Rat (nom x / neg d) (den x / neg d));
Rat (nom x / d) (den x / d)
func string : Rat -> String =
\x
if (den x == 1) (string (nom x));
string (nom x) ++ "/" ++ string (den x)
func // : Int -> Int -> Rat =
\a \b
norm (Rat a b)
func neg : Rat -> Rat =
\x
Rat (neg; nom x) (den x)
func inv : Rat -> Rat =
\x
Rat (den x) (nom x)
func + : Rat -> Rat -> Rat =
\x \y
((nom x * den y) + (nom y * den x)) // (den x * den y)
func - : Rat -> Rat -> Rat =
\x \y
x + neg y
func * : Rat -> Rat -> Rat =
\x \y
(nom x * nom y) // (den x * den y)
func / : Rat -> Rat -> Rat =
\x \y
x * inv y
func == : Rat -> Rat -> Bool =
\x \y
(den x == den y) && (nom x == nom y)
func != : Rat -> Rat -> Bool =
\x \y
(den x != den y) || (nom x != nom y)
func < : Rat -> Rat -> Bool =
\x \y
(nom x * den y) < (nom y * den x)
func <= : Rat -> Rat -> Bool =
\x \y
(nom x * den y) <= (nom y * den x)
func > : Rat -> Rat -> Bool =
\x \y
(nom x * den y) > (nom y * den x)
func >= : Rat -> Rat -> Bool =
\x \y
(nom x * den y) >= (nom y * den x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment