A proposal: Sumtypes

Dukc ajieskola at gmail.com
Mon Feb 19 17:51:57 UTC 2024


On Saturday, 17 February 2024 at 02:46:26 UTC, Richard (Rikki) 
Andrew Cattermole wrote:
>
> What I tried to do was to make it a set. Some places you want a 
> set to merge, some you don't.
>
> ```d
> sumtype S1 = int;
> sumtype S2 = int | float;
>
> S1 s1 = 1;
> S2 s2 = s1;
> ```
>
> That to me makes sense, both sets contain int, it'll be a 
> common operation that people will want to do.
>
> So the question I have is why would this not be appropriate 
> behavior, and instead should error?

It does not have to error, it makes sense per se. It just mixes 
poorly with having to name the sum type. Consider enums:

```D
enum E1 { a, e = 4 }
enum E2 { a, d = 3, e, f }
```

You can't impliclitly assign an instance of `E1` to `E2` either 
even though all legal members of E1 are representable in E2. On 
the other hand, if you just declared two bunches of `enum int`s, 
you could exchange them in the same variable.

In the same way, if I have to give a type a name, I'd expect it 
won't implicitly convert to anything. If the sum types were, by 
default, declared without a type name then I wouldn't be bothered.

>
> More importantly, if you did want to do it, how do you do it 
> without doing a match, then assign the value? Especially when 
> all the compiler would need to do is codegen a blit (or with 
> copy constructor call if provided).

S2 can well accept an assignment from an `int` (or `float`). It's 
assigning `S1` directly, without explicitly fetching the `int` 
from inside that I'm criticising. In the source code fetching 
that `int` from `S1` is going to require a match (like any use of 
a sum type outside unsafe pointer casts), but since there is only 
one member the compiler can optimise that out.



More information about the Digitalmars-d mailing list