29
$\begingroup$

While playing around with the solutions to this question, I've found some very strange behaviour:

MatchQ[3,_?Composition[Not,OptionQ]]
(*
==> False
*)
MatchQ[3,_?(Not[OptionQ[#]]&)]
(*
==> True
*)
Composition[Not,OptionQ][3]
(*
==> True
*)

So what's wrong with the first pattern? Or did I just find some bug?

$\endgroup$

1 Answer 1

31
$\begingroup$

Because PatternTest binds very tightly. You need extra parentheses:

MatchQ[3, _?(Composition[Not, OptionQ])]
$\endgroup$
8
  • $\begingroup$ Thanks. I should have thought of that possibility myself ... $\endgroup$
    – celtschk
    Commented Feb 13, 2012 at 16:44
  • 7
    $\begingroup$ @celtschk This is not at all obvious - it binds stronger than a function call: a?f[b] // FullForm gives PatternTest[a,f][b], which is not something we are used to. I just happened to have been bitten by this a few times. The same story with the Function: have to wrap it in parentheses as well. I actually mentioned that in my answer to the question you linked. $\endgroup$ Commented Feb 13, 2012 at 16:46
  • 8
    $\begingroup$ This is one reason I tend to use Condition for anything that isn't completely trivial... $\endgroup$ Commented Feb 13, 2012 at 16:46
  • $\begingroup$ @Brett I use PatternTest in this form with parentheses quite a bit as well, but I agree that there are less chances for errors with Condition. $\endgroup$ Commented Feb 13, 2012 at 16:50
  • 5
    $\begingroup$ It's unusual for something to have a higher precedence than [...] function call ... $\endgroup$
    – Szabolcs
    Commented Feb 13, 2012 at 16:50

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.