draft proposal for Sum Types for D

Walter Bright newshound2 at digitalmars.com
Wed Nov 30 03:53:05 UTC 2022


On 11/29/2022 6:45 AM, Timon Gehr wrote:

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

Ok


> - introspection, e.g. is(T==sumtype)

Already in the DIP

> and __traits(allMembers, ...)

Ok


> - 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 propose a (future) match statement instead. Sumtypes and match statements are 
symbiotically joined at the hip. I realize this proposal is somewhat crippled 
without the match, but I didn't want to put the time into designing the match if 
sumtypes are DOA.


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

An immutable sumtype could not have its members reassigned.

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

Yes.



More information about the Digitalmars-d mailing list