A proposal: Sumtypes

ryuukk_ ryuukk.dev at gmail.com
Fri Feb 9 16:13:12 UTC 2024


On Thursday, 8 February 2024 at 19:26:37 UTC, Timon Gehr wrote:
>> ```d
>> sumtype S = int i | long l;
>> 
>> S s = :i = 2;
>> ```
>> ...
>
> I would strongly advise to drop this.


I agree, i'd make it an error and ask user to be explicit

>> 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.
>
>> 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.
>
>> To merge two sumtypes together use the pipe operator on the 
>> type.
>> 
>> ```d
>> sumtype S1 = :none | int i;
>> sumtype S2 = :none | long l;
>> alias S3 = S1 | S2; // :none | int i | long l
>> ```
>> ...
>
> The flattening behavior is unintuitive.
>
>
>> 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.


I agree, multiple ways to do the same thing will lead to confusion


More information about the Digitalmars-d mailing list