Skip to main content
1 of 7
rcollyer
  • 34.3k
  • 7
  • 95
  • 198

Condition has three forms in which it can be used in defining a function:

  1. f[x_Integer /; EvenQ[x] && Positive[x]] := x+1,
  2. f[x_Integer] /; EvenQ[x] && Positive[x] := x+1, and
  3. f[x_Integer] := x+1 /; EvenQ[x] && Positive[x]

which are interpreted slightly differently by Mathematica. For instance, the first form results in the Pattern, x_Integer, being interpreted as

Condition[Pattern[x,Blank[Integer]], And[EvenQ[x],Positive[x]]] 

or, in short hand

Condition[ x_Integer, EvenQ[x] && Positive[x]] 

The second form looks like,

Condition[f[x_Integer], EvenQ[x] && Positive[x]] := x + 1 

The third form is interpreted as,

f[x_Integer] := Condition[ x + 1, EvenQ[x] && Positive[x]] 

They all give identical results. The timings reveal a slightly different tale:

f0[x_Integer?(And[EvenQ[#], Positive[#]] &)] := x + 1 f1[x_Integer /; EvenQ[x] && Positive[x]] := x + 1 f2[x_Integer] /; EvenQ[x] && Positive[x] := x + 1 f3[x_Integer] := x + 1 /; EvenQ[x] && Positive[x] rnds = RandomInteger[{-10, 10}, 1000000]; Timing[f0 /@ rnds;] Timing[f1 /@ rnds;] Timing[f2 /@ rnds;] Timing[f3 /@ rnds;] (* {1.75124, Null} {1.41897, Null} {1.4107, Null} {2.17659, Null} *) 

The timings for f1 and f2 do exhibit some volatility, and occasionally exceed the timing for f0, but, for the most part, are consistently faster than PatternTest. The timing for f3 is always slower, much slower.

rcollyer
  • 34.3k
  • 7
  • 95
  • 198