I have imported a vector math library, and would like to add my own (*) and (+) operators while preserving the existing operators for basic int and float.
I have tried the following:
let inline (*) (x : float) (y : Vector) = y.Multiply(x)
let inline (*) (x : Vector) (y : float) = x.Multiply(y)
let inline (+) (x : Vector) (y : Vector) = x.Add(y)
Which has two problems:
- It seems to remove
int + int
andint * int
, and - The 2nd line (which is intended to complete commutativity) does not compile because it is a "duplicate definition".
How can I go about defining some commutative operators on my imported Vector type while also not losing these operations on ints and floats?
(I want to be able to write generic code elsewhere using * and +, without having to specify float/Vector/int type constraints).
You need to define the operators inside your type - i.e.
etc.
Then all will work as you expect
If you are able to modify source code of the library, it's simpler to add a few overloads via type extensions:
However, if the first operand has a primitive type (e.g your first example), overloading resolution doesn't work any more.
At any rate, you can exploit member overloading and propagate constraints to an inline function:
This works for existing types with
(*)
since we preserve them in the last static member. You can do the same for(+)
operator.This technique works even when you cannot modify the
Vector
type.