I want to define a method shared by all members of a discriminated union. Currently I've implemented it like this, but it seems really inelegant- surely there is a better way. Suggestions?
type A =
{AData:string}
member this.SharedMethod (x:float) : int= ...
type B =
{BData:float}
member this.SharedMethod (x:float) : int= ...
type AB =
| A of A
| B of B
let CallSharedMethod (ab:AB) x =
match ab with
| AB.A(a') -> a'.SharedMethod x
| AB.B(b') -> b'.SharedMethod x
What about something like this?
This assumes that you want each variant of your sum type (aka discriminated union) to do something different with the float parameter.
For the case of
A
, I just return the original value since there's not much else I can do (since there is no generally useful relationship betweenstring
andfloat
that yields afloat
).