bool concat patternmatching with switch

Quirin Schroll qs.il.paperinik at gmail.com
Wed Jun 5 12:57:18 UTC 2024


On Tuesday, 4 June 2024 at 20:08:13 UTC, monkyyy wrote:
> On Tuesday, 4 June 2024 at 15:55:50 UTC, Quirin Schroll wrote:
>> On Tuesday, 28 May 2024 at 19:39:45 UTC, monkyyy wrote:
>>> ```d
>>> switch(i%3==0,i%5==0){
>>>   case 1,1: return "fizzbuzz";
>>>   case 0,1: return "buzz";
>>>   case 1,0: return "fizz";
>>>   case ?,?: return i.to!string;
>>> }
>>> ```
>>
>> Two points: You need parens around the case stuff: `case 
>> (0,1):` because `case 0,1:` already exists and means `case 0: 
>> case 1:`.
>>
>> I filed an [enhancement 
>> issue](https://issues.dlang.org/show_bug.cgi?id=24585) for the 
>> basic idea. It’s just a lowering that the front-end can do and 
>> doesn’t require a DIP.
>>
>> I guess your idea with the `?` is the only part that needs a 
>> DIP. (In your example, one could use `default:` though.)
>
> I kinda doubt its a mere enhancment, d has the dumb c style 
> switches that are thin abstractions of goto; this will require 
> a preprocessing step that im unsure if it exists at all 
> currently

Your `switch` could be:
```d
switch (((i%3==0) << 1) | (i%5==0))
{
     case (1 << 1) | 1: return "fizzbuzz";
     case (0 << 1) | 1: return "buzz";
     case (1 << 1) | 0: return "fizz";
     default:           return i.to!string;
}
```
The transformation is mechanical and absolutely trivial, and it’s 
the same “dumb C-style switch” it has always been. For string 
switching, something more nuanced is needed, but string switches 
are special anyway.


More information about the dip.ideas mailing list