1 people like it.
Like the snippet!
Simple type arithmetic with Peano numbers.
Simple type arithmetic with Peano numbers, using a recursive type and pattern matching over it.
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:
|
type Peano = Zero | Succ of Peano
with
static member op_Explicit(source: Peano) : int =
let rec desugar =
function
| Zero -> 0
| Succ x -> 1 + desugar x
desugar source
override this.ToString() =
sprintf "%d" (int this)
let rec add a b =
match a, b with
| Zero, b -> b
| Succ a, b -> Succ (add a b)
let rec mult a b =
match a, b with
| a, Zero -> Zero
| a, Succ b -> add a (mult a b)
(*
* Examples:
*)
let five = add (Succ(Succ(Succ(Zero)))) (Succ(Succ(Zero)))
let fiveAsInt = int five
let report = sprintf "the result is %s" (five.ToString())
let ten = mult (Succ(Succ(Zero))) (Succ(Succ(Succ(Succ(Succ(Zero))))))
let report' = sprintf "the result is %d" (int ten)
|
union case Peano.Zero: Peano
union case Peano.Succ: Peano -> Peano
type Peano =
| Zero
| Succ of Peano
override ToString : unit -> string
static member op_Explicit : source:Peano -> int
Full name: Script.Peano
static member Peano.op_Explicit : source:Peano -> int
Full name: Script.Peano.op_Explicit
val source : Peano
Multiple items
val int : value:'T -> int (requires member op_Explicit)
Full name: Microsoft.FSharp.Core.Operators.int
--------------------
type int = int32
Full name: Microsoft.FSharp.Core.int
--------------------
type int<'Measure> = int
Full name: Microsoft.FSharp.Core.int<_>
val desugar : (Peano -> int)
val x : Peano
val this : Peano
override Peano.ToString : unit -> string
Full name: Script.Peano.ToString
val sprintf : format:Printf.StringFormat<'T> -> 'T
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.sprintf
val add : a:Peano -> b:Peano -> Peano
Full name: Script.add
val a : Peano
val b : Peano
val mult : a:Peano -> b:Peano -> Peano
Full name: Script.mult
val five : Peano
Full name: Script.five
val fiveAsInt : int
Full name: Script.fiveAsInt
val report : string
Full name: Script.report
override Peano.ToString : unit -> string
val ten : Peano
Full name: Script.ten
val report' : string
Full name: Script.report'
More information