Enumerated Unions (sum types)
Paul Backus
snarwin at gmail.com
Thu Sep 12 09:56:44 UTC 2024
On Thursday, 12 September 2024 at 09:40:14 UTC, Dukc wrote:
> 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.
Leaving the tag implementation unspecified allows the compiler to
optimize it out.
You can use them in foreign languages by defining an extern(C)
API and treating the content as opaque.
> 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.
By "tag type" I assume you mean the type of the __tag property.
Is there any practical difference between what you describe and
just using size_t?
> 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.
I agree. Ideally, you would use pattern matching to access the
fields. But that's a whole separate DIP.
> 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 agree. I'll add to the DIP that the assignment operator should
behave like this.
> 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.
I agree that void fields should be allowed, but that should be a
separate DIP, not part of a sum type proposal. They should be
allowed for structs and classes too.
More information about the dip.ideas
mailing list