draft proposal for Sum Types for D

Timon Gehr timon.gehr at gmx.ch
Fri Dec 2 19:44:07 UTC 2022


On 12/2/22 06:23, Walter Bright wrote:
> On 11/29/2022 6:45 AM, Timon Gehr wrote:
>> 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.
> 
> In defense, I would add that Rust appears to just the same thing. Except 
> that Rust pointers can't be null.

Which makes it not a special case. I would have been on board if the 
goal was to add non-null pointers.

> I do understand the notion that a quirk may cause problems.
> 

It would cause problems in generic 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);
>> }
> 
> I know, but the syntax is a bit unappealing. How about:
> 
> sumtype Nullable { Null = null, int* Ptr }
> 
> where the `= null` triggers the special case, as it is not an integer.
> ...

Well, as long as it is explicit somehow and by default the behavior is 
not special it should work.

>> 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.
> 
> What you get is a better error message than seg fault.
> ...

It's a spectrum. ;)

compile-time error > runtime error with stack unwinding > runtime error 
without stack unwinding > segfault

>> Therefore, I really think D should statically enforce that the user 
>> checks the tag.
> 
> The user isn't going to want to do that if he knows the tag is correct.

I am a user and I am absolutely going to prefer having to explicitly 
check the tag before I access it. It's so much more useful. Compile-time 
errors are great for refactoring. Any amount of dynamic typing is a hassle.

> Array buffer overflow checks are also hidden from the user.
> 

Well, this is not my preference, but I guess the type system is not 
tracking value ranges across statements. Anyway, additional compiler 
support is useful even if it does not allow proving every single 
correctness property.


More information about the Digitalmars-d mailing list