A proposal: Sumtypes
Richard (Rikki) Andrew Cattermole
richard at cattermole.co.nz
Thu Mar 7 18:49:11 UTC 2024
On 08/03/2024 12:59 AM, cc wrote:
> On Thursday, 8 February 2024 at 15:42:25 UTC, Richard (Rikki) Andrew
> Cattermole wrote:
>> sum types
>
> In D there is a case where a variable can be declared in a condition,
> e.g. `if (auto a = someFunc) a.doWhatever;`. Could similar logic like
> this work?
>
> ```d
> sumtype Foo = int | float | string;
> Foo foo;
> foo = 2;
> assert(foo is int);
> assert(foo !is float);
>
> void barFloat(float) {}
> Foo getPi() => {
> if (userIsBaker)
> return "apple";
> return 3.14f;
> }
>
> foo = getPi();
> barFloat(foo); // Illegal, use:
> if (foo is float) { // inside this scope, accesses to foo treat it as float
> barFloat(foo); // ok now!
> } else if (foo is string) {
> writefln("Sure could go for some %s PIE...", foo.toUpper);
> }
> writefln("handy foo debugger: %s", foo); // template/trait magic would
> make this ok though and format to library standards. static if
> (is(typeof(arg) == sumtype)) ... etc
> ```
It could be made to work yes.
However for matching, I'm waiting on Walter before having opinions about it.
More information about the Digitalmars-d
mailing list