draft proposal for Sum Types for D

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


On 11/29/2022 6:42 AM, Timon Gehr wrote:
> Nice!

Wow! I expected you to eviscerate it! :-)

> I think this general design, where it behaves just like a tagged union but 
> @safe, makes 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 expect that when a user accesses s.member, he implicitly expects it to be that 
member. If it isn't, then it's a program bug and hence a fatal runtime error. 
Adding an assert() in front of it is redundant.


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

The compiler could do:

     writeln(s.a);
     writeln(s.b); // compile time error

with data flow analysis, because if all paths to the second use go through 
reading s.a, then s.b could not possibly be valid. It would be similar to:

     if (x == 0)
     {
         if (x == 1) deadCode();
     }

which currently dmd does not do.


More information about the Digitalmars-d mailing list