Sum type, the D way

Walter Bright newshound2 at digitalmars.com
Tue Nov 29 20:17:21 UTC 2022


On 11/29/2022 11:40 AM, deadalnix wrote:
> On Tuesday, 29 November 2022 at 18:58:59 UTC, Walter Bright wrote:
>> My original sumtype design was indeed extending the enum. But eventually, 
>> trouble surfaced. For example, the pattern matching that goes on with types, 
>> such as for IsExpressions, and for template parameters. Suddenly, existing 
>> code that is expecting an enum would match a sumtype, likely causing problems.
> I'm sure this can be sorted out.

I'm a lot less sure. I expect a barrage of corner cases nobody expected. It's 
also confusing to users - they've come to expect how enums behave, and suddenly 
it's different.

There's also the issue of when is it an enum and when is it an enum subtype. The 
syntax gives it away, but in my experience, I expect endless confusion.

Calling it "sumtype" is also clarifying what it is. It is not some special enum. 
It's a sumtype, making it clear that D supports sumtypes. Naming things clearly 
is very important. People already have in their minds what an enum is, and it's 
not a sumtype.

Remember when we decided to use "enum" to declare manifest constants? It made a 
lot of sense from a programming point of view to do that, but users found it 
very confusing.


>> Another problem is, as you mentioned, the open nature of enums, which won't 
>> work with sumtypes.
> It already doesn't work today, with things like final switch. You have the power 
> to fix it.

By breaking a lot of existing code, particularly the common use of flags. I 
would expect a lot of unhappy users.


> This is exactly why I'm telling you to not roll out sum types right now. You are 
> building on top of quick sands.

Building a new type is not building on quick sand. It's a clean sheet.


>> Then there's the issue of implicit casting of enums to their basetype. Not 
>> sure sumtypes are implicitly convertible.
> I don't understand what the issue is here.

enums are eager to convert to their base type. sumtypes are not, in fact, the 
base type of a sumtype cannot be determined at compile time.


>> So then it just seemed simpler with a lot fewer special cases to make sumtypes 
>> a separate entity. One problem that does resolve, is they'll be closed, which 
>> I think you'll like :-)
> 
> Making the whole thing a special case doesn't typically translates into fewer 
> special cases.

It makes for a much more understandable design, because the two aren't mixed up 
with if statements. They become separate topics.



More information about the Digitalmars-d mailing list