sumtypes for D

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


On 11/29/2022 3:56 PM, Vladimir Panteleev wrote:
> On Monday, 28 November 2022 at 09:27:11 UTC, Walter Bright wrote:
>> I've written most of a DIP for one. Should I:
> 
> I really wish that instead of adding more language features, we would improve 
> the language so that things like this are implementable *in* the language.

There is std.sumtype

https://dlang.org/phobos/std_sumtype.html


> I'm not sure about the argument that not everyone might use the same type if 
> it's implemented as a custom type. Even if one were to argue that not everyone 
> uses Phobos, the implementation can go into Druntime, which is an extension of 
> the compiler, which solves this problem.

In general you're correct. But sometimes, it's a big win to put things into the 
language. Two examples: ddoc and unittest. The conventional wisdom at the time 
was these certainly should not be part of the core language.


> The example in the DIP about null pointers is wrong. It can still be useful to 
> distinguish between non-null pointers, null pointers, and some third state such 
> as "no pointer". `Nullable!(Nullable!(Nullable!int)) foo` is perfectly valid.

True, but the draft design doesn't prevent doing that.


> We don't even need a standardized `NonNull` type or trait or whatever. Leverage 
> existing D features instead:
> 
> ```d
> template nullIsValid(T)
> {
>      static if (is(T == struct))
>          enum nullIsValid = {
>              try
>              {
>                  union U
>                  {
>                      ubyte[T.sizeof] bytes = 0;
>                      T t;
>                  }
>                  U u;
>                  assert(u.t); // call invariant
>                  return true; // no exception was thrown - null is a valid state
>              }
>              catch (Throwable e)
>                  return false; // exception was thrown - null is an INVALID state
>          }();
>      else
>          enum nullIsValid = true;
> }
> ```
> 
> or something like that. Currently it doesn't work because you can't call struct 
> invariants directly, and can't catch `assert(false)` in CTFE. But, these are 
> fixable and examples of things that would improve metaprogramming at a 
> fundamental, building-block level and enable building more cool high-level types 
> and data structures, not just sum types.

True, but I wouldn't have a null pointer violation be anything but a fatal 
error, not a catchable exception.



More information about the Digitalmars-d mailing list