Skip to content

Instantly share code, notes, and snippets.

@Mroik
Last active September 30, 2023 11:43
Show Gist options
  • Save Mroik/7ca3b8d96abc7c2901e67c455df610d6 to your computer and use it in GitHub Desktop.
Save Mroik/7ca3b8d96abc7c2901e67c455df610d6 to your computer and use it in GitHub Desktop.
type natural = Z | S of natural;;
exception NoSolutionInNatural;;
let rec sum a b =
match b with
| Z -> a
| S x -> sum (S a) x
;;
let rec sub a b =
match b with
| Z -> a
| S x ->
match a with
| Z -> raise NoSolutionInNatural
| S y -> sub y x
;;
let rec mult a b =
match b with
| Z -> Z
| S Z -> a
| S x -> mult a x |> sum a
;;
let rec enumerate_n =
let rec loop x = fun () -> Seq.Cons (x, loop (S x)) in
loop Z
;;
type rational = Q of natural * natural;;
exception NoSolutionInRational;;
let rec qsum a b =
match a, b with
| Q (_, Z), _ -> raise NoSolutionInRational
| _, Q (_, Z) -> raise NoSolutionInRational
| Q (x, d1), Q (y, d2) when d1 = d2 -> Q (sum x y, d1)
| Q (x, d1), Q (y, d2) ->
let num1 = mult x d2 in
let num2 = mult y d1 in
let num = sum num1 num2 in
let den = mult d1 d2 in
Q (num, den)
;;
let rec qmult a b =
match a, b with
| Q (_, Z), _ -> raise NoSolutionInRational
| _, Q (_, Z) -> raise NoSolutionInRational
| Q (n1, d1), Q (n2, d2) -> Q (mult n1 n2, mult d1 d2)
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment