draft proposal for Sum Types for D

Timon Gehr timon.gehr at gmx.ch
Tue Nov 29 14:45:09 UTC 2022


On 11/29/22 07:26, Walter Bright wrote:
> Go ahead, Make My Day! Destroy!
> 
> https://github.com/WalterBright/DIPs/blob/sumtypes/DIPs/1NNN-(wgb).md


Some things that are missing:

- non-default construction, e.g.:

sumtype Result{
     error,
     int value;
}

auto result1 = Result.error;
auto result2 = Result.value(2);

The above is a bit unergonomic, maybe there is a better way to expose 
those constructors. They should exist though, otherwise it is e.g., 
impossible to initialize an immutable sumtype.


- introspection, e.g. is(T==sumtype) and __traits(allMembers, ...)

- in particular, it would be nice to provide access to the associated 
enumeration and the tag, e.g. for Result above, there could be an 
automatically generated enum like this:

enum Result{
     error,
     value,
}

Then you could do something like:

final switch(tag(result)) {
     case Tag!Result.error: ...
     case Tag!Result.value: ...
}

This way, sumtype can be a drop-in replacement for existing unsafe 
tagged unions. I guess with __traits(allMembers, ...) this can be done 
in the library, but nothing beats direct access to the tag.

- how does it interact with type qualifiers? In particular, I guess you 
can have a sumtype with only immutable members and reassign them anyway?


- pattern matching (though that's acknowledged in the DIP and can 
probably be designed later)



More information about the Digitalmars-d mailing list