I have 3 types, A
, B
, and C
in F#. Two of the types, A
and B
I do not have the ability to modify code for. Type C
is a type that I control.
I with to write overloaded operators such as -
type C () =
static member (><) (alpha : A) (beta : B) : C = zeta alpha beta
static member (><) (beta : B) (alpha : A) : C = omega alpha beta
When I attempt to invoke the operator, the compile issues the following error -
Error FS0043 None of the types 'A, B' support the operator '><'
How can I workaround the issue such that I can define overloaded operators with operands whose type definitions I do not control? The only type whose definition I do control is the result type, C
!
Since C
doesn't appear in the input parameters it won't work, at least as long as type extensions are not taken into account in overload resolution with trait calls.
So you'll have to include C
and define the operator at global level:
type A = A
type B = B
type C () = class end
let zeta _ _ = C ()
let omega _ _ = C ()
type C with
static member (><) (_:C, alpha : A) = fun (beta : B) -> zeta alpha beta : C
static member (><) (_:C, beta : B) = fun (alpha : A) -> omega alpha beta: C
let inline (><) x y = (Unchecked.defaultof<C> >< x) y
// Test
let x = A >< B
// val x : C
Note: you can use a different operator name internally if you want
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With