sumtypes for D

Timon Gehr timon.gehr at gmx.ch
Tue Nov 29 14:03:48 UTC 2022


On 11/29/22 08:26, Walter Bright wrote:
> On 11/28/2022 6:53 PM, Adam D Ruppe wrote:
>> Curious, what did you find lacking in std.sumtype?
>>
>> Same question to Walter.
> 
> It's addressed in the draft DIP I just posted.
> 
> https://github.com/WalterBright/DIPs/blob/sumtypes/DIPs/1NNN-(wgb).md
> 
> I did email std.sumtype's author, Paul Backus, for his observations but 
> have not heard back yet.

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