predSwitch

Returns one of a collection of expressions based on the value of the switch expression.

choices needs to be composed of pairs of test expressions and return expressions. Each test-expression is compared with switchExpression using pred(switchExpression is the first argument) and if that yields true - the return expression is returned.

Both the test and the return expressions are lazily evaluated.

predSwitch
(
alias pred = "a == b"
T
R...
)

Parameters

switchExpression T

The first argument for the predicate.

choices R

Pairs of test expressions and return expressions. The test expressions will be the second argument for the predicate, and the return expression will be returned if the predicate yields true with switchExpression and the test expression as arguments. May also have a default return expression, that needs to be the last expression without a test expression before it. A return expression may be of void type only if it always throws.

Return Value

Type: auto

The return expression associated with the first test expression that made the predicate yield true, or the default return expression if no test expression matched.

Throws

If there is no default return expression and the predicate does not yield true with any test expression - SwitchError is thrown. SwitchError is also thrown if a void return expression was executed without throwing anything.

Examples

1 string res = 2.predSwitch!"a < b"(
2     1, "less than 1",
3     5, "less than 5",
4     10, "less than 10",
5     "greater or equal to 10");
6 
7 assert(res == "less than 5");
8 
9 //The arguments are lazy, which allows us to use predSwitch to create
10 //recursive functions:
11 int factorial(int n)
12 {
13     return n.predSwitch!"a <= b"(
14         -1, {throw new Exception("Can not calculate n! for n < 0");}(),
15         0, 1, // 0! = 1
16         n * factorial(n - 1) // n! = n * (n - 1)! for n >= 0
17         );
18 }
19 assert(factorial(3) == 6);
20 
21 //Void return expressions are allowed if they always throw:
22 import std.exception : assertThrown;
23 assertThrown!Exception(factorial(-9));

Meta

Suggestion Box / Bug Report