I'm trying to define an overloaded operator, e.g. |+|
, as the following:
let inline ( |+| ) (m1 : #IMeasurable) (m2 : #IMeasurable) = m1.Measure + m2.Measure
The problem is, I can't do something like:
let three = m1 |+| m2 |+| m3
Because the operator |+|
isn't defined for the case (m1 : int) (m2 : #IMeasurable)
. Is there a way to overload this operator or use static type constraints to make the above expression possible? Is there a way to modify IMeasurable
(which I can edit) so that this is possible? Anything else that would allow the above expression to work?
Thank you.
Not tested, since I don't have IMeasurable, but it may do the job.
If you're defining an operator that behaves like
+
then I think the best design is to define an operator that returns a value of the same type as is the type of its arguments. This means that I would change the operator to returnIMeasurable
instead ofint
:This will make the operator definition more uniform and easier to use. The code you wanted to write will now work (returning
IMeasurable
), but you can also useSeq.reduce
:That said, if you really want to overload an operator that is defined using
let
and you cannot add it to a type as static member (because you cannot modify the type), then you'll need to use the trick that Gustavo describes