Tuple.Create in F #

I noticed a rather strange method behavior System.Tuple.Createin F #. When viewing the MSDN documentation, it indicates that the return type matters System.Tuple<T>. However, when using this method in F #, all overloads except Tuple.Create(T)will be returned 'T1 * 'T2. Obviously, calling the constructor Tuple<T>returns Tuple<T>. But I do not understand how the return type Tuple.Creatediffers from F #.

+4
source share
1 answer

The tuple type F # (syntax tuple) is compiled as System.Tuple<..>. Thus, they are of the same type at the .NET level, but for the F # type system they are different types: the type of the syntax tuple will not match the type System.Tuple<..>, but their runtime type will be the same.

You can find a detailed description in F # spec

Example c new System.Tuple<'t>()does not return a syntax tuple, perhaps because you are explicitly creating a specific type, and you should get just that.

Here are some tests:

let x = new System.Tuple<_,_>(2,3) // Creates a Tuple<int,int>
let y = System.Tuple.Create(2,3)   // Creates a syntactic tuple int * int

let areEqual = x.GetType() = y.GetType() // true

let f (x:System.Tuple<int,int>) = ()
let g (x:int * int) = ()

let a = f x
let b = g y

// but

let c = f y 
//error FS0001: The type 'int * int' is not compatible with the type 'Tuple<int,int>'

let d = g x
// error FS0001: This expression was expected to have type int * int but here has type Tuple<int,int>  

So, at compile time they are different, but at runtime they are the same. Therefore, when you use .GetType(), you get the same result.

+6
source

All Articles