C++ pattern matching is coming

Timon Gehr timon.gehr at gmx.ch
Sun Oct 23 23:21:06 UTC 2022


On 10/23/22 21:28, Walter Bright wrote:
> On 10/23/2022 3:43 AM, IGotD- wrote:
>> Can they reuse switch? In Swift they have pattern matching but they 
>> use the switch keyword for their jack-of-all-trades switch statement. 
>> Problem with C++ (and D) is that the switch statement is fallthrough 
>> by default. In order to fix this historical mistake they need a 
>> complete new keyword.
>>
>> This is something to fix in D3, remove fallthrogh by default.
> 
> Fallthrough by default was removed from D many years ago.
> 
> The awkward problem with re-using switch is that each case does not 
> introduce a new scope.

Actually, each case does introduce a new scope:

```d
int main(){
     int x;
     switch(x){
         case 0:
             int y;
             break;
         case 1:
             int y;
             break;
         default:
             int y;
             break;
     }
     return 0;
}
```

(You get compiler errors trying to compile that as C code, but not when 
you try to compile it as D code.)

https://dlang.org/spec/statement.html#switch-statement
 > The ScopeStatementList introduces a new scope.

Not sure if it has always been this way (it seems my frontend that I 
mostly developed ~10 years ago does fail to introduce a new scope).

> This raises all kinds of problems when using 
> pattern matching to declare new variables.
> 
> A second awkward problem is that case statements can be placed inside 
> nested scopes.
> 
> It's better to just leave switch as it is, and develop a new construct 
> for pattern matching that hews to modern sensibilities.

I agree with this though. Another problem is that switch cases are not 
ordered and are supposed to be disjoint. But for pattern matching, the 
semantics is usually to try each pattern in order, where patterns can 
overlap and you are supposed to put more specific patterns earlier.

Of course, one could think about additionally adding some pattern 
support to switch, where the compiler checks that all patterns are 
disjoint, but does not seem very nice to use. Also seems like somewhat 
of a hassle to implement.


More information about the Digitalmars-d mailing list