Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int64 doesn't support LanguagePrimitives.DivideByInt?

Why int64 doesn't support LanguagePrimitives.DivideByInt? I thought it would be pretty natural to write something like this:

let inline DivBy2 n = LanguagePrimitives.DivideByInt n 2
let res = DivBy2 100L

But compiler says that int64 doesn't support the operator DivideByInt.

I've tried to cheat with:

type System.Int64 with 
    static member DivideByInt (n: System.Int64) (d: int) = n / (int64 d)

But it doesn't work.

What can be done to perform generic division of int64 by int?

like image 962
Dmitrii Lobanov Avatar asked May 04 '26 02:05

Dmitrii Lobanov


2 Answers

Looking at the F# source code, the type int64 is not included in the function DivideByInt, I don't know why.

You can defining another generic function like this:

open LanguagePrimitives
type DivExtension = DivExtension of int with
    static member inline (=>) (x             , DivExtension y) = DivideByInt x y
    static member        (=>) (x:int64       , DivExtension y) = x / (int64 y)
    static member        (=>) (x:DivExtension, DivExtension y) = x

let inline DivByInt x y = x => DivExtension y

Or you can even shadow the original DivideByInt function:

let inline DivideByInt x y = x => DivExtension y

Note you can also add more overloads (ie for int), in which case you don't need the last "dummy" overload to infer the right signature.

like image 192
Gus Avatar answered May 05 '26 15:05

Gus


I've received an answer from Don Syme (via fsbugs email) when I've asked about missing MutliplyByInt and limited support of DivideByInt:

Don's answer:

This operator exists to support “Seq.averageBy” etc. This represents pseudo-precise division of the total by the count. We didn’t extend the mechanism beyond what was needed for that.

So it looks like I've misunderstood the purpose of this mechanism. But I still don't know why there's no support for int64 for DivideByInt, that means that we're limited in generic operations on int64 type. Perhaps I'm confused because int64 looks like a primitive type when it's not a primitive type. And DivideByInt is defined only for primitive types, that's why there's no support for it.

like image 30
2 revsDmitry Lobanov Avatar answered May 05 '26 14:05

2 revsDmitry Lobanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!