I'd like to be able to extend types from other libraries with static methods to enable generic arithmetic. Take, for example, the newly minted SIMD-friendly fixed-size VectorN
types from Microsoft. They define Zero
, they define (+)
, they define (/)
, but I can't use Array.average
on them because they don't define DivideByInt
, which I'd be happy to:
open System.Numerics
type Vector2f with
static member DivideByInt (v:Vector2f) (i:int) = v / Vector2f(single i, single i)
let bigArray : Vector2f[] = readABigFile()
printf "the average is %A" (Array.average bigArray)
But it won't let me compile, complaining
error FS0001: The type 'Vector2f' does not support the operator 'DivideByInt'
Why does this limitation exist in the F# compiler?
(Edit: essentially the same question was asked previously.)
DivideByInt
needs to be an operator rather than a function. Maybe try either defining an operator, or I thinkop_DivideByInt
might work. – NosologyDivideByInt
isn't a valid name for an operator in F# – VivavivaceDivideByInt (v:Vector2f,i:int)
(tuple form) work? I have got a minimal example with type extensions that works. – Nosology