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

Dukc ajieskola at gmail.com
Tue Jun 16 19:15:24 UTC 2020


On Tuesday, 16 June 2020 at 16:26:14 UTC, Paul Backus wrote:
> Here's how I would write it:
>
>     float common1(float value)
>     {
>         // Lots of code that manipulates 'value'
>     }
>
>     float common2(float value)
>     {
>         // More code that manupulates 'value'
>     }
>
>     float special(string s, float value)
>     {
>         // Do something special for only one of the types,
>         // but after doing lots of common things
>     }
>
>     float myFun(SumType!(float, int, string, int[]) a)
>     {
>         import std.functional: pipe;
>
>         return a.match!(
>             number => cast(float) number,
>             (string s) =>
>                 s.process
>                     .common1
>                     .pipe!(value => special(s, value))
>                     .common2
>             (int[] ia) =>
>                 ia.process
>                     .common1
>                     .common2
>         );
>     }

Despite my need to use the tag value directly, I do agree that 
this style should be preferable.

I am not generally very fond of littering code with extra 
variables, that converting `switch`es directly to `match`s or 
`visit`s requires. But keeping the general code architecture as 
good as in your example, should mostly avoid that need. And even 
if I do need extra variables, it should be no problem when such 
logic is encapsulated well enough.

Something to consider for me, regardless of which of the two DUB 
packages I end up using in the long term.


More information about the Digitalmars-d mailing list