This is documentation for Mathematica 4, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.2)
Wolfram Research, Inc.

Putting Constraints on PatternsFlat and Orderless Functions

2.3.6 Patterns Involving Alternatives

Specifying patterns that involve alternatives.

This defines h to give p when its argument is either a or b.

In[1]:= h[a | b] := p

The first two cases give p.

In[2]:= {h[a], h[b], h[c], h[d]}


You can also use alternatives in transformation rules.

In[3]:= {a, b, c, d} /. (a | b) -> p


Here is another example, in which one of the alternatives is itself a pattern.

In[4]:= {1, x, x^2, x^3, y^2} /. (x | x^_) -> q


When you use alternatives in patterns, you should make sure that the same set of names appear in each alternative. When a pattern like (a[x_] | b[x_]) matches an expression, there will always be a definite expression that corresponds to the object x. On the other hand, if you try to match a pattern like (a[x_] | b[y_]), then there will be a definite expression corresponding either to x, or to y, but not to both. As a result, you cannot use x and y to refer to definite expressions, for example on the right-hand side of a transformation rule.

Here f is used to name the head, which can be either a or b.

In[5]:= {a[2], b[3], c[4], a[5]} /. (f:(a|b))[x_] -> r[f, x]


Putting Constraints on PatternsFlat and Orderless Functions