1 people like it.

Type inference test

Trying to understand why some type inference used to work in OCaml and not anymore in F#

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
type Number = Zero | Integer of int | Float of float;;
let add n1 n2 =
    match n1, n2 with
    | Zero, n | n, Zero -> n
    | Integer i1, Integer i2 -> Integer (i1+i2)
    | Float f1, Float f2 -> Float (f1+f2)
    | Float f1, Integer i2 -> Float (f1 + (float i2))
    | Integer i1, Float f2 -> Float ((float i1) + f2);;

let i = 1;;
let f = 2.0;;

add i f;;

(* In OCaml: yields 3.0
   In F#: error -> "error FS0001: This expression was expected to have type
    Number    
but here has type
    int" 
*)
union case Number.Zero: Number
union case Number.Integer: int -> Number
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<_>
union case Number.Float: float -> Number
Multiple items
val float : value:'T -> float (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.float

--------------------
type float = System.Double

Full name: Microsoft.FSharp.Core.float

--------------------
type float<'Measure> = float

Full name: Microsoft.FSharp.Core.float<_>
val add : n1:Number -> n2:Number -> Number

Full name: Script.add
val n1 : Number
val n2 : Number
val n : Number
val i1 : int
val i2 : int
val f1 : float
val f2 : float
val i : int

Full name: Script.i
val f : float

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

More information

Link:http://fssnip.net/io
Posted:10 years ago
Author:Lasher`
Tags: type inference , ocaml