A proposal: Sumtypes

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Sat Feb 17 10:00:25 UTC 2024


On 09/02/2024 8:26 AM, Timon Gehr wrote:
> On 2/8/24 16:42, Richard (Rikki) Andrew Cattermole wrote:
>> ## Nullability
>>
>> A sum type cannot have the type state of null.
>> ...
> 
> I am not sure what that means.

It comes from type state theory.

What it means in the context of D is: ``s is null`` doesn't exist.

It also removes the temptation that the entry is considered for the null 
check.

https://en.wikipedia.org/wiki/Typestate_analysis

>> ## Set Operations
>>
>> A sumtype which is a subset of another, will be assignable.
>>
>> ```d
>> sumtype S1 = :none | int;
>> sumtype S2 = :none | int | float;
>>
>> S1 s1;
>> S2 s2 = s1;
>> ```
>> ...
> 
> This seems like a strange mix of nominal and structural typing.

It is a mix yes.

It is based around the entries being a set.

Something almost all D programmers will be familiar with and should be 
easily explainable.

>> This covers other scenarios like returning from a function or an 
>> argument to a function.
>>
>> To remove a possible entry from a sumtype you must peform a match 
>> (which is not being proposed here):
>>
>> ```d
>> sumtype S1 = :none | int;
>> sumtype S2 = :none | int | float;
>>
>> S1 s1;
>> S2 s2 = s1;
>>
>> s2.match {
>>      (float) => assert(0);
>>      (default val) s1 = val;
>> }
>> ```
>>
>> To determine if a type is in the set:
>>
>> ```d
>> sumtype S1 = :none | int;
>>
>> pragma(msg, int in S1); // true
>> pragma(msg, :none in S1); // true
>> pragma(msg, "none" in S1); // true
>> ```
>> ...
> 
> I think a priori here you will have an issue with parsing.

I don't know, in expression already exist, this would be a different 
version that is differentiated at semantic analysis. I wouldn't be 
surprised if it already parses with my member of operator PR.

>> Or you can expand a sumtype directly into another:
>>
>> ```d
>> sumtype S1 = :none | int i;
>> sumtype S2 = :none | S1.expand | long l; // :none | int i | long l
>> ```
>>
>> When merging, duplicate types and names are not an error, they will be 
>> combined.
>> Although if two names have different types this will error.
>> ...
> 
> Again this mixes nominal and structural typing in a way that seems 
> unsatisfying. Note that different struct types do not become assignable 
> just because they share member types and names.

A struct is not a set, a sumtype and with that this design is based upon 
being a set in terms of options.



More information about the Digitalmars-d mailing list