Search code examples
genericsf#inlineinteger-division

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?


Solution

  • 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.