What is a "reverse" to MatchQ? MatchQ converts pattern into boolean function. So how to convert back?
Suppose I want to use boolean function in Switch.
Answer
To convert a Boolean test function such as PrimeQ or IntegerQ into a pattern one typically uses either Condition (/;) or PatternTest (?). There are specific strengths and purposes for each which are described in: Using a PatternTest versus a Condition for pattern matching.
Here is a simple and brief example of each:
Cases[Range@10, _?PrimeQ]
{2, 3, 5, 7}
Cases[Range@10, x_ /; PrimeQ[x]]
{2, 3, 5, 7}
Be aware that the PatternTest operator ? has unusually high binding power as seen in this table and with:
Precedence[PatternTest]
680.
Comments
Post a Comment