Hacker News new | ask | show | jobs
by adrian_b 73 days ago
These are discriminated unions, even if they may be not Rust-style.

You can see in the examples, how "switch" uses the implicit discriminant of the union to select the code branch that must be executed, depending on the current type of the value stored in an union.

The syntax of the "switch" seems acceptable, without too many superfluous elements. It could have been made slightly better, by not needing dummy variables that must be used for selecting structure members (or used in whichever else expression is put in the right hand side; the repetition of the dummy variable names could have been avoided if the name of the union variable could have been reused with a different meaning within a "switch", i.e. as a variable of the selected type).

I do not see what else do you want. Perhaps Rust has reused the traditional term "discriminated unions", which had been used for many decades before Rust, and which means the same thing as the more recent terms "tagged unions" or "sum types", with a non-standard meaning and you have that in mind.

1 comments

I don't think these are discriminated. From the docs:

> Union types — exhaustive matching over a closed set of types

> Closed hierarchies — exhaustive matching over a sealed class hierarchy

> Closed enums — exhaustive matching over a fixed set of enum values

I believe the last one would be sum types (disc. unions). This one allows overlapping types.

The word "discriminated" means that at run time, if you receive a value whose type is a union of types you can discriminate which is the actual type of the value, so you can use that value in expressions that expect a specific type, not a union of types.

This is in contrast with what is called "union" in the C language, where you must know a priori the type of a value in order to use it correctly.

Moreover, if you can discriminate at run time which is the actual type, that means that you can discriminate between values that happen to have the same representation, but which come from distinct types, e.g. if you had a union between "signed integer" and "unsigned integer", you could discriminate between a signed "3" and an unsigned "3".

This property ensures that the number of possible values for a discriminated union type is the sum of the numbers of possible values for the component types, hence the alternative name "sum type", unlike for a non-discriminated union, where the number of possible values is smaller, because from the sum you must subtract the number of possible values of the intersection sets.

The C# unions described in the article are discriminated unions, except that their component types are not the types literally listed in their definition. If some of the component types are optional, than the true union components are the corresponding non-optional types, together with the null a.k.a. void type, which I find as a rather strange choice.