draft proposal for Sum Types for D
Basile.B
b2.temp at gmx.com
Wed Nov 30 14:22:08 UTC 2022
On Wednesday, 30 November 2022 at 08:49:00 UTC, Andrey Zherikov
wrote:
> On Tuesday, 29 November 2022 at 06:26:20 UTC, Walter Bright
> wrote:
>> Go ahead, Make My Day! Destroy!
>>
>> https://github.com/WalterBright/DIPs/blob/sumtypes/DIPs/1NNN-(wgb).md
>
>> cannot produce compile time error if not all the arms are
>> accounted for in a pattern match rather than a thrown exception
>
> It does:
> ```d
> SumType!(int, string) s;
> s.match!((int i) => true); // Error: static assert: "No
> matching handler for types `(string)`"
> ```
>
>> `if (?x.busy)`
>
> Please consider moving `?` to be after identifier so the
> following can be allowed:
> ```d
> sumtype C
> {
> Default,
> int value
> }
> sumtype B
> {
> Default,
> C c
> }
> sumtype A
> {
> Default,
> B b
> }
>
> A a;
> if(a.b?.c?.value?)
> ...
> ```
>
> Compare with `if(?a.b && ?a.b.c && ?a.b.c.value)`
>
> This will also allow natural improving of ternary expression:
> `a.b?:123` === `(a.b?) ? (a.b) : (123)`. (may be just `a.b ?
> 123`?)
>
> Also if you even think about adding optional type, `?`-suffix
> will perfectly match here:
> ```d
> int? optional;
> if(optional?)
> writeln("it's set to ", optional);
>
> string? s;
> writeln("the value is ", s?:"not set");
> ```
That would not generally work, or that would not be efficient. In
the background "optional access" allocates a default value at the
use site, meanings an alloca, and then you select the default or
the right one if evaluation has succeed. Optional access is more
tied to the language. Optional access does not generate good
unoptimized code, let's not making its D version worst that what
already exists.
You see a thing like
a?.b = c
is like
typeof(a.b) fallback;
(a.b ? a.b : fallback) = c;
where the ternary yields a lvalue.
This causes problems with members that will be eventually used in
optional accesses. The default value must be related to that
particular expression.
Using a sum type for optional access is still a hack.
More information about the Digitalmars-d
mailing list