1 people like it.

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: 
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)

(*
 * Examples:
*)
let five = add (Succ(Succ(Succ(Zero)))) (Succ(Succ(Zero)))
let fiveAsInt = int five
let report = sprintf "the result is %s" (five.ToString())
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 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
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/sq
Posted:8 years ago
Author:Giacomo Stelluti Scala
Tags: types