3
$\begingroup$

This question already has an answer here:

I'm stuck in a seemingly easy question, but I can't figure out why the GreaterThan function and the pattern test do not work. I have tried to debug it for a while, but I can't understand why.

f[a_?GreaterThan[0]] := "!"

f[6] (*return f[6] itself*)
$\endgroup$

marked as duplicate by Mr.Wizard pattern-matching Jul 5 '18 at 19:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    $\begingroup$ perhaps you could try f[a_?(#>0&)]:="!"; also check Greater and PatternTest (hint: whatever follows the ? must return a boolean value) $\endgroup$ – yosimitsu kodanuri Jul 5 '18 at 15:23
  • 5
    $\begingroup$ Triple click on GreaterThan. Then the lack of a parenthesis is revealed. I.e. f[a_?(GreaterThan[0])] := "!" $\endgroup$ – Coolwater Jul 5 '18 at 16:14
  • $\begingroup$ ? is an incredibly high precedence operator (even more so that [...]. It binds the GreaterThan instead of GreaterThan[0]. $\endgroup$ – b3m2a1 Jul 5 '18 at 16:17
5
$\begingroup$

It's a problem with the precedence of operators. You need a set of parentheses to specify that the [0] part is to apply to GreaterThan instead of to the whole PatternTest expression:

Clear[f]
f[a_?(GreaterThan[0])] := "!"
f[6] (* ! *)

You can see the difference in FullForm:

FullForm[a_?GreaterThan[0]]                         (* no parentheses   *)
FullForm[a_?(GreaterThan[0])]                       (* with parentheses *)

returns:

PatternTest[Pattern[a, Blank[]], GreaterThan][0]    (* no parentheses   *)
PatternTest[Pattern[a, Blank[]], GreaterThan[0]]    (* with parentheses *)

? has very high precedence, in particular higher than [] (see this Operator precedence table) .

$\endgroup$
  • $\begingroup$ Thanks! By the way, why is the possible reason that WRI decide to give ? a rather high precedence? $\endgroup$ – Eric Jul 5 '18 at 17:10
  • $\begingroup$ @Eric Glad it helps. Also, I don't know enough about programming language design to answer that. $\endgroup$ – MarcoB Jul 5 '18 at 17:24

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