Last active
June 13, 2019 14:20
-
-
Save ntreu14/3032b96ad5288fb7b3257f9aa62d1b76 to your computer and use it in GitHub Desktop.
Solution to CodeWars peano numbers kata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Peano = | |
| Zero | |
| Succ of Peano | |
// Comapre | |
let rec cmp x y = | |
match x, y with | |
| Zero, Zero -> 0 | |
| Zero, Succ _ -> -1 | |
| Succ _, Zero -> 1 | |
| Succ a, Succ b -> cmp a b | |
// Addition | |
let rec add x y = | |
match x, y with | |
| Zero, Zero -> Zero | |
| Succ a, Zero | |
| Zero, Succ a -> Succ a | |
| Succ _, Succ b -> add (Succ x) b | |
// Subtraction | |
let rec sub x y = | |
match x, y with | |
| Zero, Zero -> Zero | |
| Succ _, Zero -> x | |
| Zero, Succ _ -> failwith "negative number" | |
| Succ a, Succ b -> sub a b | |
// Multiplication | |
let rec mul x y = | |
match x, y with | |
| Zero, _ | |
| _, Zero -> Zero | |
| Succ _, Succ b -> add x (mul x b) | |
// Integer division | |
let rec div x y = | |
if y = Zero then failwith "divide by 0" | |
elif cmp x y = 0 then Succ Zero | |
elif cmp x y = -1 then Zero | |
else add (Succ Zero) (div (sub x y) y) | |
// Modulo | |
let rec modulo x y = | |
match cmp x y with | |
| 0 -> Zero | |
| -1 -> x | |
| _ -> modulo (sub x y) y | |
// Even | |
let rec even = function | |
| Zero -> true | |
| Succ Zero -> false | |
| Succ (Succ a) -> even a | |
// Odd | |
let odd = | |
not << even |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment