Why is the default argument type of arithmetic operators int?

I am new to F # and I was surprised to find that the type fxy = x + y is actually int -> int -> int . Appearance , this is due to some compromising performance.

But why is this really necessary? Why not just specify the type 'a -> 'a -> 'a or something like that? This seems to work for comparison: the type gxy = x < y is equal to x:'a -> y:'a -> bool when 'a : comparison . Why not for arithmetic operators?

Could the compiler statically infer specific primitive types from call nodes and specialize the general function from there, returning to some dynamic dispatch if this fails?

This may be very obvious, but I could not find any good resources. What are the reasons for this behavior?

+5
source share
1 answer

Yes, the default type is used for these int statements unless you specify another option or are not taken out of use. If you want to define them for all types, you must make the inline function:

 let inline fxy = x + y 

But note that the signature is:

 x: ^a -> y: ^b -> ^c when ( ^a or ^b) : (static member ( + ) : ^a * ^b -> ^c) 

This is because in .NET you cannot use member restrictions , but F # allows them at compile time. This is why you see those โ€œhat typesโ€ and the restriction that this type must have a static member (+) set.

Also note that type variables are not a -> a -> a , as you assume, because in the .NET Framework not all add operations match this signature. In other environments, such as Haskell, everything is different, adding strictly a -> a -> a , but in .NET you can add, for example, TimeSpan to DateTime:

 System.DateTime(2000,1,1) + new System.TimeSpan(1, 2, 0, 30, 0) 

and the result is DateTime, here is the signature: a -> b -> a

Comparison is a different story, because this restriction does exist at the .NET level, so it can be compiled and encoded in IL, while element restrictions must be allowed at compile time, so the function must be marked as inline.

I think you misinterpreted the explanation in a related question: this is not a performance compromise, the real reason is a system constraint like .NET. The fact that a built-in function is faster in most cases (because it is built-in by the compiler) is a secondary effect.

+7
source

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


All Articles