Output Type: functions versus types

I am learning F # and I don’t understand how sample leads and generics work in this language. For example, I can declare a generic function min and use it with parameters of different types:

let min ab = 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 the type, this will not 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 reuse the definition of common functions for different types, but not the type definition?
  • Is a function specialized for each type at runtime, e.g. using C # generics? Or at compile time, like C ++ templates? Or is boxing performed to treat each argument as IComparable?

Thanks.

+3
source share
1 answer

Classes require explicit type parameters. It 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 runtime signature is the same, minus the constraint).

< is replaced by a call to GenericLessThanIntrinsic , which has a constraint. The restriction applies only to callers.

In addition, from section 14.6.7 of the specification:

Generalization is the process of defining a typical type to determine where possible, which makes the construct reusable with several different types. Generalization is used by default in all definitions of functions, values, and members , except as noted below in this section. Generalization also applies to member definitions that implement common virtual methods in object expressions.

(in italics)

Note that classes are not listed. I believe that this does not give a reason, but it is by design.

+6
source

Source: https://habr.com/ru/post/915719/


All Articles