I have a function that can return different types, and I use a discriminatory union for this. What I need is a conversion from one type into a discriminatory union into another type. In addition, some types can be converted to all other types (String), but some of them can only be converted to String (MyCustomType)
To do this, I added the member ConvertTo method to ResultType :
type MyTypes = | Boolean = 1 | Integer = 2 | Decimal = 3 | Double = 4 | String = 5 | MyCustomType = 6 type ResultType = | Boolean of bool | Integer of int | Decimal of decimal | Double of double | String of string | MyCustomType of MyCustomType with member this.ConvertTo(newType: MyTypes) = match this with | ResultType.Boolean(value) -> match newType with | MyTypes.Boolean -> this | MyTypes.Integer -> ResultType.Integer(if value then 1 else 0) ... | ResultType.MyCustomType(value) -> match newType with | MyTypes.MyCustomType -> this | MyTypes.String -> ResultType.String(value.ToString()) | _ -> failwithf "Conversion from MyCustomType to %s is not supported" (newType.ToString())
I donβt like this design, because if I add more types, it requires me to make a lot of changes: MyTypes, ResultType, as well as in several places in the ConvertTo member function.
Can anyone suggest a better solution for this type conversion?
Thank you in advance
source share