Are float array, float[], and double[] different, or the same?
I'm writing my code as if these are all the same thing, and having no problems, but it's starting to confuse me when I hover over a function in Visual Studio and see that the type definitions contain 3 different types that I had thought were all the same.开发者_JS百科 Are they the same? Or are they different?
They are the same. See the type abbreviations at the bottom of the FSharp.Core documentation. float = double = System.Double
and array<'T> = 'T[]
. You can also define your own type abbreviations and use them the same way:
type dbl = double
let (d:dbl) = 1.0
You didn't ask about it, but note that the one place where type abbreviations might not work quite like you'd expect is measure types; float<_>
is defined independently of float
, double
, and System.Double
, and there's no such thing as a corresponding double<_>
or System.Double<_>
.
In addition to type abbreviations, there are two useful things to know about F# types. First of all, there are two ways to write names of generic types. One way is to use the OCaml syntax and the second way is to use the .NET syntax:
- When using .NET syntax, you write
array<'T>
or for exampleOtherType<'T1, 'T2>
(for types with more than one generic type parameter). - In the OCaml syntax, the same thing is written as
'T array
or('T1, 'T2) OtherType
These two notations are equivalent - when you declare a value of type annotated using the .NET syntax, you can assign it to a value annotated using the OCaml syntax. 'T[]
is a special notations for arrays, but this explains why array<'T>
is the same as 'T array
.
The second thing is that F# uses a bit unfortunate naming for floating-point number types. This is probably due to the compatibility with OCaml, but it can easily confuse .NET programmers:
- F# float type corresponds to
System.Double
in .NET (which is calleddouble
in C#) - F# float32 type corresponds to
System.Single
in .NET (which is calledfloat
in C#)
As @kvb points out, double is another type alias for the System.Double
type.
精彩评论