We can use list comprehensions to simulate a switch statement.
This pattern has an number of
if conditions or guards in a list
and then selects the
By doing so, we emulate a switch statement from other languages.
Be advised that all conditional statements will be evaulated.
A basic example
This example demonstrates turning a integer into a string describing its numerical classification.
order example, we show our work by breaking down the pattern.
While a “true” prefix has the correct result, we can see that
b are the same, HasPrefix still matches
and we get the less accurate result.
An uncovered case errors
We can modify our first example to demonstrate what happens when you forget the default, or otherwise fail to cover all conditions.
All conditions are evaluated
You might expect the following to work rather than error. This is the result of all conditions being evaulated. That is, there is not short-circuit to the evaluation.