Improvements to switch
Nick Treleaven
nick at geany.org
Wed Apr 17 10:54:40 UTC 2024
On Tuesday, 16 April 2024 at 18:25:45 UTC, Meta wrote:
> case string: "" -> writeln("empty string"); // Naming the
> value is optional
Presumably we could leave off the type:
```d
case : "" -> writeln("empty string");
```
Though we might want to require an identifier or `_` when there
is a type.
So we'd have this grammar:
```
Case:
case Pattern -> Statement
case Type? Identifier Pattern? -> Statement
Pattern:
`:` AssignExpression
`if` `(` AssignExpression `)`
```
> int[3] staticArr = [1, 2, 3];
> switch (staticArr) {
> case int[N], size_t N -> writeln("Static int array of size
> ", N);
Could have type inference too, like for template parameter
inference.
```d
case T[N] _, T, alias N -> writeln("Static ", T.stringof, "
array of size ", N);
```
Inferred symbols would be listed after matching values.
> case string[] s: ["D", rest...] -> writeln(rest); //
> Prints ["rocks", "!"]
So `rest` would be typed `string[]`.
> case string[] s: ["D", mid..., "!"] -> writeln(mid); //
> Prints "rocks"
I think `mid` cannot be variadic in order for it to be typed
`string`. So it would be:
```d
case string[] s: ["D", mid, "!"] -> writeln(mid); // Prints
"rocks"
```
More information about the dip.ideas
mailing list