Type inference: functions vs types

Deadly 提交于 2019-12-14 01:19:29

问题


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.


回答1:


Classes require explicit type parameters. This works:

type Point2D<'T>(x:'T, y:'T) = 
    member this.X = x
    member this.Y = y

let float32Point = Point2D(0.0f, 1.0f)
let intPoint = Point2D(0, 1)

To answer your second question, your definition of min has the signature 'a -> 'a -> 'a (requires comparison). The comparison constraint exists only at compile-time (the run-time signature is the same, minus the constraint).

< is replaced with a call to GenericLessThanIntrinsic, which has the constraint. The constraint is merely propagated to callers.

Also, from section 14.6.7 of the spec:

Generalization is the process of inferring a generic type for a definition where possible, thereby making the construct reusable with multiple different types. Generalization is applied by default at all function, value, and member definitions, except where listed later in this section. Generalization also applies to member definitions that implement generic virtual methods in object expressions.

(emphasis added)

Notice, classes are missing from the list. I suppose it doesn't give the rationale, but it is by design.



来源:https://stackoverflow.com/questions/10588506/type-inference-functions-vs-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!