sumtypes for D

Timon Gehr timon.gehr at gmx.ch
Tue Nov 29 14:01:43 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.

Nice! I think this general design, where it behaves just like a tagged 
union but @safe, makes some sense for D. I _really_ wish bad element 
access resulted in a compile-time error instead of a runtime error though.

Basically, you could treat

if(?s.member){

}

and

assert(?s.member);

specially, and only allow accesses to s.member if they are guarded by 
one of them. By default, accessing members is disallowed. The user can 
then choose between:

if(?s.member){
     writeln(s.member);
}

and

assert(?s.member);
writeln(s.member);

To either check the tag manually or opt into the runtime error very 
explicitly.

I think catching errors early during type checking is one of the most 
compelling things about sum types in other languages, and it would be 
great if D could get that in some way. The analysis does not have to be 
particularly sophisticated. In particular, no control flow analysis is 
required.


More information about the Digitalmars-d mailing list