Pattern Test (x_?Positive), (y_Real?Positive)

PatternTest is closely related to Condition.  PatternTest is used to specify that a certain pattern must meet a  certain condition.  So for example in the next cell (f) is defined when given  an argument that is a positive number.

Clear[f, s]  f[x_ ? Positive] := x + 1  {f[2], f[8.3], f[π/2], f[(-2)^(1/2)]}

{3, 9.3, 1 + π/2, f[ 2^(1/2)]}


In the next example (f) is only defined when given an argument that is a
positive integer.

Clear[f, s]  f[x_Integer ? Positive] := x + 1  {f[2], f[8.3], f[π/2], f[(-2)^(1/2)]}

{3, f[8.3], f[π/2], f[ 2^(1/2)]}


In the next example (f) is defined when given an argument that is a positive
integer or a positive real number.

Clear[f, s]  f[x : ((_Integer | _Real) ? Positive)] := x + 1  {f[2], f[8.3], f[π/2], f[(-2)^(1/2)]}

{3, 9.3, f[π/2], f[ 2^(1/2)]}

In some cases we want to use a test that isn't a built-in unary operator  (Positive, NumericQ, AtomQ, ...).  In that case we can use a pure function as in the next example.  In the next example (f) is only defined when  given an argument that is an integer between 0 and 10.

Clear[f, s]  f[x_Integer ? (0<#<10&)] := x + 1  {f[2], f[25], f[8.3], f[π/2], f[(-2)^(1/2)]}

{3, f[25], f[8.3], f[π/2], f[ 2^(1/2)]}


In the next cell (f) is only defined when given an argument of any type
between 0 and 10.  Can you see why we need the part about (Im[#]===0) ?

Clear[f, s]  f[x_ ? (Im[#] === 0&&0<#<10&)] := x + 1  {f[2], f[25], f[8.3], f[π/2], f[(-2)^(1/2)]}

{3, f[25], 9.3, 1 + π/2, f[ 2^(1/2)]}


We can't use pattern variables in the test portion of (Pattn/;Test), and that
is why the definition in the next cell isn't used.

ClearAll[foo] ;  foo[x_ ? (0<x<1)] := x^2  foo[0.4]

foo[0.4]


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page