A proposal: Sumtypes
cc
cc at nevernet.com
Thu Mar 7 11:59:38 UTC 2024
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
```
More information about the Digitalmars-d
mailing list