Tagged unions [Was: What's wrong with std.variant.Variant?]
Stanislav Blinov
stanislav.blinov at gmail.com
Tue Jun 16 15:35:41 UTC 2020
On Tuesday, 16 June 2020 at 12:44:54 UTC, Simen Kjærås wrote:
> On Tuesday, 16 June 2020 at 12:21:56 UTC, Paul Backus wrote:
>> If it's not too much trouble, can you give an example of the
>> kind of thing you'd like to be able to do? I suspect it's
>> possible with SumType, but it may not be obvious how, which
>> makes it a good candidate for the documentation's "examples"
>> section.
>
> I'm not Dukc, but here's an example I came up with:
>
> float myFun() {
> MyTaggedUnion!(float, int, string, int[]) a = fun();
>
> float value;
> final switch (a.type) {
> case a._float:
> return a.as!float();
> case a._int:
> return a.as!int();
> case a._string:
> value = a.as!string().process();
> case a._intArray:
> value = a.as!(int[]).process();
> }
>
> // Lots of code that manipulates 'value'.
> if (a.type == a._string) {
> // Do something special for only one of the types,
> // but after doing lots of common things
> }
> // More code that manipulates 'value'.
>
> return value;
> }
>
> Essentially, there's shortcut returns for a few cases, but the
> others have some common behavior, even better if this is
> slightly different in one single place for one single held
> type, so you can't really factor it out as a separate function.
I wonder how that final switch would look like if the tagged
union contains a type such as Some!(Other!(immutable(int)[]), 3).
I.e. how would you spell out the case :)
More information about the Digitalmars-d
mailing list