I am learning F# and I don’t understand how type inference and generics work in this language. For example, I can declare a generic min function and use it with parameters of different types:
let min a b = if a < b then a else b
let smallestInt = min 3 5
let smallestFloat = min 3.0 5.0
But if I try the same thing with a type, it doesn’t work:
type Point2D(x, y) =
member this.X = x
member this.Y = y
let float32Point = new Point2D(0.0f, 1.0f)
let intPoint = new Point2D(0, 1) // This expression was expected to have type
// float32 but here has type int
So, I have a few questions:
- Why can I re-use the generic function definition for different types but not the type definition?
- Is the function specialized for every type at run-time like with C# generics? Or at compile-time like C++ templates? Or is boxing performed to treat every argument as IComparable?
Thanks.
Classes require explicit type parameters. This works:
To answer your second question, your definition of
minhas the signature'a -> 'a -> 'a (requires comparison). Thecomparisonconstraint exists only at compile-time (the run-time signature is the same, minus the constraint).<is replaced with a call toGenericLessThanIntrinsic, which has the constraint. The constraint is merely propagated to callers.Also, from section 14.6.7 of the spec:
(emphasis added)
Notice, classes are missing from the list. I suppose it doesn’t give the rationale, but it is by design.