Immutable fields in discriminatory union

I know that you can add methods and properties to discriminatory joins, but can you add an immutable field that must be set when the join instance is created, like the fields in a record?

I assume that I would like to combine the union type and the record type, for example:

type union = | OptionOne of int | OptionTwo of string { AFieldUsedForBothCases : string } 

which is not a valid declaration.

I know that this can be solved by creating a record type:

 type record = { AFieldUsedForBothCases : string TheDiscriminatedUnion : union } 

but I would like to do something similar to the first example, if possible.

+4
source share
3 answers

No, I don’t think so, but you can add it in both cases and extract it with a member:

 type union = | OptionOne of int * string | OptionTwo of string * string member u.AFieldUsedForBothCases = match u with | OptionOne (_,s) | OptionTwo(_,s) -> s 

In the end, you must specify an additional element in your constructor. Well, this will allow you to repeat the common element for each constructor, but I think this is not so bad.

+5
source

I think this is a tidier solution

 type union= |a of int |b of string type Realtype = string * union 

Thanks to type checking, you can force settings, and I think it is slightly ahead of the write solution

+3
source

I do not think that's possible. In addition, I think that your second code (using records) makes much more sense, because DU is β€œthis or that or what ...”, now if there is something in common between all these cases, then I would keep this common thing from DU, not inside DU.

+1
source

All Articles