Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
1  
@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. –  Leonid Shifrin Jan 19 '13 at 12:47
    
@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. –  Mr.Wizard Jan 19 '13 at 15:50
    
@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. –  Leonid Shifrin Jan 19 '13 at 15:58

1 Answer 1

up vote 5 down vote accepted

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.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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