View source code
Display the source code in std/algorithm/comparison.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.algorithm.comparison.predSwitch

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

auto predSwitch(alias pred, T, R...) (
  T switchExpression,
  lazy R choices
);

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.

Parameters

NameDescription
switchExpression The first argument for the predicate.
choices 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.

Returns

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.

Example

string res = 2.predSwitch!"a < b"(
    1, "less than 1",
    5, "less than 5",
    10, "less than 10",
    "greater or equal to 10");

writeln(res); // "less than 5"

//The arguments are lazy, which allows us to use predSwitch to create
//recursive functions:
int factorial(int n)
{
    return n.predSwitch!"a <= b"(
        -1, {throw new Exception("Can not calculate n! for n < 0");}(),
        0, 1, // 0! = 1
        n * factorial(n - 1) // n! = n * (n - 1)! for n >= 0
        );
}
writeln(factorial(3)); // 6

//Void return expressions are allowed if they always throw:
import std.exception : assertThrown;
assertThrown!Exception(factorial(-9));

Authors

Andrei Alexandrescu

License

Boost License 1.0.