draft proposal for Sum Types for D

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

 >

BTW: I understand extraordinarily well where the desire for supporting 
an explicitly nullable pointer comes from, but I worry that integrating 
it into the more general syntax implicitly is a bit too cute. It will 
lead to bad interactions in generic code.

E.g.:

sumtype WithDefault(T){
     Default;
     T Value;
}

A user does not expect this to behave specially if `T` is a pointer. 
Generic code would have to explicitly check for that case and manually 
undo the rewrite in the library. I don't want to read the resulting 
unwieldy Phobos code.

Explicitly nullable pointers are too good of a feature to just give up 
though, so instead, you could introduce explicit syntax for the null check.

E.g.:

sumtype Nullable{
     Null,
     int* Ptr;
     invariant(Ptr !is null);
}

The semantics of this would be to check the invariant on assignment and 
if it fails, then default-initialize the type instead. There could be 
multiple invariants that each can only refer to one of the members.

Then this would be distinct from:

sumtype DoublyNullable{
     Null,
     int* Ptr;
}

It would also be more general because it allows enforcing more general 
invariants. (But it could also be limited to the special case with null, 
at least in the beginning; what's important is that the different 
behavior is documented explicitly in a difference in syntax.)

Note that with the semantics where a bad member access is a runtime 
error, you don't gain much over just using a raw pointer. Therefore, I 
really think D should statically enforce that the user checks the tag.


More information about the Digitalmars-d mailing list