Enumerated Unions (sum types)

Dukc ajieskola at gmail.com
Thu Sep 12 10:24:01 UTC 2024


On Thursday, 12 September 2024 at 09:56:44 UTC, Paul Backus wrote:
>
> You can use them in foreign languages by defining an extern(C) 
> API and treating the content as opaque.

Yes, if the foreign language will only handle it via a pointer. 
But if the ABI is nailed down, the foreign language can have the 
sum type on an array or at the stack, and pass them to D 
functions by value.

>
> I agree. Ideally, you would use pattern matching to access the 
> fields. But that's a whole separate DIP.

Pattern matching is complex enough that I agree it's best as it's 
own DIP. But I think this DIP still needs the simple getter 
function since a language-level sum type really doesn't carry 
it's weight if it is too low-level. We already have `union` for 
the low-level work.

If you insist, IMO the DIP doesn't necessarily have to specify 
what exactly the getter function must do, because in the end it's 
just an utility function. But at least it must be proposed that 
one should be added to the language or the standard library.

>
> I agree. I'll add to the DIP that the assignment operator 
> should behave like this.

I was initially thinking about assignment operator too, but 
there's a problem. You might have two or more fields with the 
same type, in which case assigning a value of that type to the 
sum type is ambiguous. If you instead/also mean an assignment to 
*field* of the sum type, then that avoids the problem.

>
> 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.

...and if they are, we don't need the annoying special case that 
the setter wouldn't take a value argument for `void` fields. I 
think it's worth mentioning in the DIP though as a future 
development, once/if you submit it for real.


More information about the dip.ideas mailing list