Putting Constraints on Patterns

The Wolfram Language provides a general mechanism for specifying constraints on patterns. All you need to do is to put /;condition at the end of a pattern to signify that it applies only when the specified condition is (RefLink[True, paclet:ref/True]). You can read the operator /; as "slash-semi", "whenever", or "provided that".

Putting conditions on patterns and transformation rules.

This gives a definition for fac that applies only when its argument n is positive:

fac[n_/;n>0]:=n!

The definition for fac is used only when the argument is positive:

fac[6]+fac[-4]

This gives the negative elements in the list:

Cases[{3,-4,5,-2},x_/;x<0]

You can use /; on whole definitions and transformation rules, as well as on individual patterns. In general, you can put /;condition at the end of any := definition or :> rule to tell the Wolfram Language that the definition or rule applies only when the specified condition holds. Note that /; conditions should not usually be put at the end of = definitions or -> rules, since they will then be evaluated immediately, as discussed in "Immediate and Delayed Definitions".

Here is another way to give a definition that applies only when its argument n is positive:

fac2[n_]:=n!/;n>0

Once again, the factorial functions evaluate only when their arguments are positive:

fac2[6]+fac2[-4]

You can use the /; operator to implement arbitrary mathematical constraints on the applicability of rules. In typical cases, you give patterns which structurally match a wide range of expressions, but then use mathematical constraints to reduce the range of expressions to a much smaller set.

This rule applies only to expressions that have the structure v[x_,1-x_]:

v[x_,1-x_]:=p[x]

This expression has the appropriate structure, so the rule applies:

v[a^2,1-a^2]

This expression, while mathematically of the correct form, does not have the appropriate structure, so the rule does not apply:

v[4,-3]

This rule applies to any expression of the form w[x_,y_], with the added restriction that y==1-x:

w[x_,y_]:=p[x]/;y==1-x

The new rule does apply to this expression:

w[4,-3]

In setting up patterns and transformation rules, there is often a choice of where to put /; conditions. For example, you can put a /; condition on the right-hand side of a rule in the form lhs:>rhs/;condition, or you can put it on the left-hand side in the form lhs/;condition->rhs. You may also be able to insert the condition inside the expression lhs. The only constraint is that all the names of patterns that you use in a particular condition must appear in the pattern to which the condition is attached. If this is not the case, then some of the names needed to evaluate the condition may not yet have been "bound" in the pattern-matching process. If this happens, then the Wolfram Language uses the global values for the corresponding variables, rather than the values determined by pattern matching.

Thus, for example, the condition in f[x_,y_]/;(x+y<2) will use values for x and y that are found by matching f[x_,y_], but the condition in f[x_/;x+y<2,y_] will use the global value for y, rather than the one found by matching the pattern.

As long as you make sure that the appropriate names are defined, it is usually most efficient to put /; conditions on the smallest possible parts of patterns. The reason for this is that the Wolfram Language matches pieces of patterns sequentially, and the sooner it finds a /; condition which fails, the sooner it can reject a match.

Putting the /; condition around the x_ is slightly more efficient than putting it around the whole pattern:

Cases[{z[1,1],z[-1,1],z[-2,2]},z[x_/;x<0,y_]]

You need to put parentheses around the /; piece in a case like this:

{1+a,2+a,-3+a}/.(x_/;x<0)+a->p[x]

It is common to use /; to set up patterns and transformation rules that apply only to expressions with certain properties. There is a collection of functions built into the Wolfram Language for testing the properties of expressions. It is a convention that functions of this kind have names that end with the letter Q, indicating that they "ask a question".

Some functions for testing mathematical properties of expressions.

The rule applies to all elements of the list that are numbers:

{2.3,4,7/8,a,b}/.(x_/;NumberQ[x])->x^2

This definition applies only to vectors of integers:

mi[list_]:=list^2/;VectorQ[list,IntegerQ]

The definition is now used only in the first case:

{mi[{2,3}],mi[{2.1,2.2}],mi[{a,b}]}

An important feature of all the Wolfram Language property-testing functions whose names end in Q is that they always return (RefLink[False, paclet:ref/False]) if they cannot determine whether the expression you give has a particular property.

4561 is an integer, so this returns (RefLink[True, paclet:ref/True]):

IntegerQ[4561]

This returns (RefLink[False, paclet:ref/False]), since x is not known to be an integer:

IntegerQ[x]

Functions like (RefLink[IntegerQ, paclet:ref/IntegerQ])[x] test whether x is explicitly an integer. With assertions like x∈(RefLink[Integers, paclet:ref/Integers]) you can use (RefLink[Refine, paclet:ref/Refine]), (RefLink[Simplify, paclet:ref/Simplify]), and related functions to make inferences about symbolic variables x.

Some functions for testing structural properties of expressions.

With ==, the equation remains in symbolic form; === yields (RefLink[False, paclet:ref/False]) unless the expressions are manifestly equal:

{x==y,x===y}

The expression n is not a member of the list {x,x^n}:

MemberQ[{x,x^n},n]

However, {x,x^n} is not completely free of n:

FreeQ[{x,x^n},n]

You can use (RefLink[FreeQ, paclet:ref/FreeQ]) to define a "linearity" rule for h:

h[a_ b_,x_]:=a h[b,x]/;FreeQ[a,x]

Terms free of x are pulled out of each h:

h[a b x,x]+h[2 (1+x) x^2,x]

Another way to constrain patterns.

The construction pattern/;condition allows you to evaluate a condition involving pattern names to determine whether there is a match. The construction pattern?test instead applies a function test to the whole expression matched by pattern to determine whether there is a match. Using ? instead of /; sometimes leads to more succinct definitions.

With this definition, matches for x_ are tested with the function (RefLink[NumberQ, paclet:ref/NumberQ]):

p[x_?NumberQ]:=x^2

The definition applies only when p has a numerical argument:

p[4.5]+p[3/2]+p[u]

Here is a more complicated definition. Do not forget the parentheses around the pure function:

q[{x_Integer,y_Integer}?(Function[v,v.v>4])]:=qp[x+y]

The definition applies only in certain cases:

{q[{3,4}],q[{1,1}],q[{-5,-7}]}

Patterns with exceptions.

This gives all elements except 0:

Cases[{1,0,2,0,3},Except[0]]

(RefLink[Except, paclet:ref/Except]) can take a pattern as an argument:

Cases[{a,b,0,1,2,x,y},Except[_Integer]]

This picks out integers that are not 0:

Cases[{a,b,0,1,2,x,y},Except[0,_Integer]]

(RefLink[Except, paclet:ref/Except])[c] is in a sense a very general pattern: it matches anything except c. In many situations you instead need to use (RefLink[Except, paclet:ref/Except])[c,patt], which restricts to expressions matching patt that do not match c.