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

Patterns Involving Alternatives

patt1|patt2|...a pattern that can have one of several forms

Specifying patterns that involve alternatives.

This defines h to give p when its argument is either a or b.
Click for copyable input
The first two cases give p.
Click for copyable input
You can also use alternatives in transformation rules.
Click for copyable input
Here is another example, in which one of the alternatives is itself a pattern.
Click for copyable input
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. If you try to match a pattern like (a[x_]|b[y_]), then there still will be definite expressions corresponding to x and y, but the unmatched one will be Sequence[ ].
Here f is used to name the head, which can be either a or b.
Click for copyable input