Why does GreaterThan with pattern test not work [duplicate]

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*)

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

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) .

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