7 people like it.

Re-creating arithmetic with DU

You never know when you might need this.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
type Nat =
  | Zero
  | Succ of Nat

let rec plus = function
  | (m,Zero) -> m
  | (m, Succ n) -> Succ (plus (m,n));;

//val plus : Nat * Nat -> Nat

//plus (Succ Zero, Succ (Succ Zero));;
//val it : Nat = Succ (Succ (Succ Zero))
let rec mult = function
  | (m,Zero) -> Zero
  | (m,Succ n) -> plus (m, mult(m,n));;

//val mult : Nat * Nat -> Nat

//mult (Succ(Succ Zero), Succ (Succ Zero));;
//val it : Nat = Succ (Succ (Succ (Succ Zero)))

let rec fact = function
  | Zero -> Succ Zero
  | Succ m -> mult (Succ m, fact m);;
//val fact : Nat -> Nat

//fact (Succ (Succ (Succ (Succ (Succ Zero)))));;
//Lots of Succs

let rec ofNat = function
  | Zero -> 0
  | Succ m -> 1 + ofNat m

//val ofNat : Nat -> int
//fact (Succ (Succ (Succ (Succ (Succ Zero))))) |> ofNat;;
//val it : int = 120
union case Nat.Zero: Nat
union case Nat.Succ: Nat -> Nat
type Nat =
  | Zero
  | Succ of Nat

Full name: Script.Nat
val plus : Nat * Nat -> Nat

Full name: Script.plus
val m : Nat
val n : Nat
val mult : Nat * Nat -> Nat

Full name: Script.mult
val fact : _arg1:Nat -> Nat

Full name: Script.fact
val ofNat : _arg1:Nat -> int

Full name: Script.ofNat
Raw view Test code New version

More information

Link:http://fssnip.net/2J
Posted:13 years ago
Author:Dmitri Pavlenkov
Tags: du , discriminated union , match