Enumerated Unions (sum types)
Dukc
ajieskola at gmail.com
Thu Sep 12 09:40:14 UTC 2024
Paul Backus kirjoitti 12.9.2024 klo 5.42:
> https://gist.github.com/pbackus/28e7f5668219ce83467c83c347ec7202
>
> This DIP proposes a conservative design for sum types that aims to be
> consistent with existing D syntax and semantics. It does not discuss
> pattern matching.
You're leaving the implementation of tag field undefined. I think it's
better to define it. That way sum types can be used in foreign language
APIs, and `sizeof(ASumType)` stays predictable.
Also I propose that the tag type is enumerated type that is implicitly
convertible to `int`. The base type is an unsigned integer type big
enough to hold all the field types. Default value and the enumerated
values (other than having one for each type) can remain unspecified though.
The user should not have to write that `get` function of the example
themselves. Otherwise we can't use the sum type from fully `@safe` code
if any of it's fields can have unsafe values. Likewise, we should have a
generic setter function for all the sum types that type safely checks
the tag, and runs the destructor of the old object if the assignment
changes the type.
I propose the DIP explicitly allows `void` fields, that work the same
way as `Void` fields of TaggedAlgebraic. The void field could be
initialised with either `void.init` or `void`. The return reference from
`get`ting a void field would point to null. Setting a sumtype to void
would simply wouldn't take a value argument.
Overall I like this approach though. Way better than the sum type
proposals of Walter and Rikki.
More information about the dip.ideas
mailing list