draft proposal for Sum Types for D
Jacob Shtokolov
jacob.100205 at gmail.com
Mon Dec 5 14:17:47 UTC 2022
On Wednesday, 30 November 2022 at 14:20:31 UTC, Quirin Schroll
wrote:
> On Tuesday, 29 November 2022 at 06:26:20 UTC, Walter Bright
> wrote:
>> Go ahead, Make My Day! Destroy!
>>
> 3. As for a keyword, you could circumvent the problem by
> re-using existing keywords. `enum union` would be a candidate.
+1 for not introducing new keywords for such a feature. The sum
type (or tagged union) in the current DIP looks somewhat like an
extended `union`, so either combination of keywords containing
`union` will work just great IMO.
If there is an urge to add new keywords, it could be like:
```d
tagged union Option(T)
{
None,
T val
}
```
or maybe `union alias` or something like that.
Another essential and already mentioned feature is extensibility:
imagine we have a typed event bus of the following configuration:
```d
alias Events = SumType!(Connected, Disconnected, TextMessage);
```
Now we want to extend it with new types of events without losing
support in the parts of the code we don't control (e.g. library
code, etc.). How would we do that?
One thing would be to redefine the type by hand: it works great
when the number of options is low, but what if there are tens or
maybe hundreds of types?
Right now it's only possible by using classes, or by introducing
a struct with discriminator/tag and a union field manually
checking (and casting) the types at runtime.
---
Also, as the current proposal implements the algebraic data type
as a C-style `union` rather than a type alias (or something like
that), giving an explicit name to each tag in the union may be
overwhelming if there are many types to be included.
More information about the Digitalmars-d
mailing list