Improvements to switch

Meta jared771 at gmail.com
Fri Apr 19 06:28:55 UTC 2024


On Wednesday, 17 April 2024 at 11:24:16 UTC, Nick Treleaven wrote:
> On Tuesday, 16 April 2024 at 18:25:45 UTC, Meta wrote:
>> - branch guards
>> - pattern match on arrays, slices:
>
> Some other things, based on section 3.3 of this C++ proposal:
> https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2392r2.pdf
>
> - Multiple alternatives that have the same result: ||
>
> E.g.
> ```d
> case :9 || :15 -> "not prime";
> ```

This is already covered by regular switch statements. You can 
write:
```D
case 9, 15 -> "not prime";
```

> - Multiple constraints required for a result: &&
>
> E.g.
> ```d
> switch (variant) {
>     case int _ && :42 -> "int and 42";
> ```

I think this would require some sort of `opMatch` function to 
allow custom unpacking of arbitrary structs/classes. Ideally it 
would allow you to do:
```D
switch (variant) {
     case int n if (n == 42) -> "int and 42";
     // Or alternatively
     case int n: 42 -> "int and 42";
}
```

> - Grouping common names and constraints: { }
>
> E.g.
> ```d
> switch (variant) {
>     case int i {
>         case if (i < 0) -> "negative int";
>         default -> "some other int";
>     }
> ```

```D
switch (variant) {
     // goto default is already a feature of regular switch 
statements
     case int i -> i < 0 ? "negative int" : goto default;
     default -> "some other int";
}
```
This will work _if_ `goto default` is typed as `noreturn`. I 
doubt that's the case, but that's something that can also be 
fixed in the compiler.


More information about the dip.ideas mailing list