Improvements to switch
Meta
jared771 at gmail.com
Tue Apr 16 18:25:45 UTC 2024
On Tuesday, 16 April 2024 at 10:34:21 UTC, ryuukk_ wrote:
> It is time to make them nice to use
>
>
> - allow them as expression
>
> ```D
> int myvalue = switch(code) {
> // ...
> };
>
> ```
>
> - more concise
>
> ```D
> switch(code) {
> case 1 -> "what";
> case 2, 3 -> "ok";
> else -> "no";
> }
> ```
>
> - pattern match
>
> ```D
> switch(tagged) {
> case A, B -> do_that();
> case C myc -> do_this(myc);
> else -> nothing();
> }
> ```
A couple more things:
- branch guards
```D
auto input = readln().strip().to!int();
auto s = switch (input) {
case n if (n == 0) -> "zero";
case n if (n > 0) -> "greater than zero";
case n if (n < 0) -> "less than zero";
};
switch (readln().strip()) {
case string: "" -> writeln("empty string"); // Naming the
value is optional
case string s: "asdf" -> writeln(s[2..$]); // Prints "df"
}
```
- pattern match on arrays, slices:
```D
int[3] staticArr = [1, 2, 3];
switch (staticArr) {
case int[N], size_t N -> writeln("Static int array of size ",
N);
case int[N], size_t N: 1 -> writeln("This branch won't be
taken");
case int[N], size_t N if (N == 1) -> writeln("Equivalent to
previous branch");
case int[2] -> writeln("This branch won't be taken either");
case string[N], N -> writeln("Nope");
}
string[] slice = ["D", "rocks", "!"];
switch (slice) {
case string[] : [] -> writeln("empty slice");
case string[] s: ["D"] -> writln(s[0]);
case string[] s: ["D", rest...] -> writeln(rest); //
Prints ["rocks", "!"]
case string[] s: ["D", mid..., "!"] -> writeln(mid); //
Prints "rocks"
case string[] s: ["D", "rocks", "!"] -> writeln(s); //
Prints ["D", "rocks", "!"]
}
```
It'd be really nice to be able to pattern match on ranges as
well, but I don't know exactly how we'd do that given how they
work.
More information about the dip.ideas
mailing list