3

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*)
MarcoB
  • 67,153
  • 18
  • 91
  • 189
Eric
  • 1,191
  • 7
  • 20

1 Answers1

6

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

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