Tagged unions [Was: What's wrong with std.variant.Variant?]

Simen Kjærås simen.kjaras at gmail.com
Tue Jun 16 12:44:54 UTC 2020


On Tuesday, 16 June 2020 at 12:21:56 UTC, Paul Backus wrote:
> On Monday, 15 June 2020 at 21:48:19 UTC, Dukc wrote:
>>> Is there a way I can improve SumType's documentation to make 
>>> its behavior in this regard clearer?
>>
>> It's not documentations fault. But if you want to supersede 
>> Taggedalgebraic really hard, you can try convincing Mike to 
>> let you write a project highlight in the D blog, to raise 
>> awareness for thickskulls like me :D.
>
> That's an interesting idea. I'll look into it after the 
> upcoming 1.0.0 release.
>
>>> In Rust's `enum` types you cannot access the tag directly.
>>
>> Again bad research from my part. But it's something I want to 
>> do. Why? `final switch` statements. I may want to `return` or 
>> `break` directly from the switch, and in that case I can't use 
>> pattern matching without extra thinking. Well, on D anyway. I 
>> don't know about Rust.
>
> 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.

--
   Simen


More information about the Digitalmars-d mailing list