5
$\begingroup$

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.

$\endgroup$
3
  • 1
    $\begingroup$ @Mr.Wizard Not sure I agree with closing of this question. If it is not an exact duplicate (i.e. wasn't asked before exactly in this form), then I think it deserves an answer and an open status, since this is a pretty common operation and some folks without lots of experience may not immediately realize the connection. You could e.g. convert some of your comments to an answer. $\endgroup$ Commented Jan 19, 2013 at 12:47
  • $\begingroup$ @Leonid in addition to your comment why didn't you vote to reopen? Also, do you have something to add that is not duplicating other answers on this site that is more than "Use e.g. _?IntegerQ or x_ /; IntegerQ[x]"? I closed this because I felt that the use of those functions was already better covered in linked question and I didn't want to repeat it here. $\endgroup$
    – Mr.Wizard
    Commented Jan 19, 2013 at 15:50
  • $\begingroup$ @Mr.Wizard I forgot :). I don't have much to add to what you mentioned. I just think that this is one of the cases where, while the question may be a basic one, it may not be obvious straight from the docs (in the sense that it may not be clear for a novice exactly where to look for it), so I think we can keep this question alive on the site. $\endgroup$ Commented Jan 19, 2013 at 15:58

1 Answer 1

6
$\begingroup$

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.
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.