std.sumtype?

Steven Schveighoffer schveiguy at gmail.com
Tue Mar 30 17:52:39 UTC 2021


On 3/30/21 1:14 PM, Paul Backus wrote:
> On Tuesday, 30 March 2021 at 17:01:29 UTC, Steven Schveighoffer wrote:
>> What might be nice is to have some simplifiers for match to prevent 
>> having to jump through the hoops.
>>
>> For example, a match flavor that throws by default, or one that 
>> ignores unhandled types. This way, you don't have to write stuff like 
>> `(_) {}` at the end of your handlers.
>>
>> FWIW, taggedalgebraic has `visit` to enforce all items are handled, 
>> and `tryVisit` that throws if at runtime it determines no visitors 
>> match the current type.
> 
> sumtype has had tryMatch [1] since version 0.4.0 (released May 2018).
> 
> For ignoring types, I have found the following utility function handy:
> 
>     void ignore(T)(auto ref T) {}
> 
> You can instantiate it explicitly to ignore a specific type:
> 
>     obj.match!(
>         ignore!A,
>         (B b) { doSomething1; },
>         (C c) { doSomething2; }
>     );
> 
> Or you can use it as a catch-all handler:
> 
>     obj.match!(
>         (A a) { doSomethingWith(a); },
>         ignore
>     );
> 
> [1] https://pbackus.github.io/sumtype/sumtype.tryMatch.html


Yeah, that actually looks pretty good. Forgive my ignorance, I have not 
looked at any depth at SumType.

I think `ignore` would be a great addition to the library, and makes the 
code much easier to read. I can't think of a `match` name that would 
look better than just specifying ignore in the list.

One thing that is sticking out via this mechanism for pattern matching 
is that with lambdas, you have to name the parameter (for everything but 
keywords) or you will not get what you are looking for. So things like 
(B b) { doSomething2; } would look nicer as (B) { doSomething2; } but 
obviously will not do what you would expect. Hence the usage of `_` in 
the previous examples.

Not sure if there might be a language improvement to help with this. It 
probably is not that common anyway.

-Steve


More information about the Digitalmars-d mailing list