If you can change the source code of the library, itβs easier to add a few overloads through type extensions:
type Vector with static member (*) (x : Vector) (y : float) = x.Multiply(y) static member (+) (x : Vector) (y : Vector) = x.Add(y)
However, if the first operand is of a primitive type (for example, your first example), permission overloading no longer works.
In any case, you can use element overloading and extend restrictions to the built-in function:
type VectorOverloadsMult = | VectorOverloadsMult static member (?<-) (VectorOverloadsMult, x: float, y: Vector) = y.Multiply(x) static member (?<-) (VectorOverloadsMult, x: Vector, y: float) = x.Multiply(y) static member inline (?<-) (VectorOverloadsMult, x, y) = x * y let inline (*) xy = (?<-) VectorOverloadsMult xy
This works for existing types with (*) , since we store them in the last static member. You can do the same for the (+) operator.
let v: Vector = ... // Declare a Vector value let a = 2.0 * v let b = v * 2.0 let c = 2 * 3 let d = 2.0 * 3.0
This method works even if you cannot change the type of Vector .
source share