Sum Type by Struct
Richard (Rikki) Andrew Cattermole
richard at cattermole.co.nz
Fri Sep 13 09:26:16 UTC 2024
On 13/09/2024 4:55 AM, Meta wrote:
> Why is this member of operator necessary? What advantages does it have
> compared to matching based on type, like the current library sumtypes
> do? How is the following:
> ```D
> alias None = typeof(null);
> sumtype S = None | int;
> sumtype S2 = int | bool;
>
> S1 s1;
> S2 s2 = s1.match {
> (None) {
> if (random() > 0.5)
> return true;
> else
> return 2;
> };
>
> (int v) {
> return v;
> };
> };
> ```
>
> Improved by the member of operator?
As a proposal, it is the only one of the three that does not require a
name to be provided. Both Walter and Paul require a name for each element.
The benefit of _optionally_ supporting names, is that when the type is
not unique in of itself, you can make it unique by adding a name.
Consider a web form, where you would want to take an email, where it
could be for personal use or business use:
```d
sumtype WebFormEmail = :DoNotContact | string personal | string business;
```
The extra name is now unique between the two, and you can have a way of
saying do not contact me, just show me the white paper.
As for your approach to aliasing null to create a non-unique type, there
is only so many sentinels in the language you can do that for and the
type of a null is itself a valid type to be in a sumtype. The closest
thing to what you are doing there is ``void`` and there is only one of them.
The type of a member of operator has a size zero, this allows eliding of
the value if all of them are size zero. The type of a null is the same
as a pointer, after all its a pointer.
Being able to elide the value, to get a sumtype down to the size of just
its tag is VERY important for error handling. See zero-cost exceptions
proposal for C++ to see why I consider us needing that.
https://open-std.org/JTC1/SC22/WG21/docs/papers/2018/p0709r0.pdf
More information about the dip.ideas
mailing list