This is documentation for Mathematica 3, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)
 Documentation / Mathematica / The Mathematica Book / Reference Guide / Patterns and Transformation Rules  /

A.5.1 Patterns

Patterns stand for classes of expressions. They contain pattern objects which represent sets of possible expressions.

Pattern objects.

When several pattern objects with the same name occur in a single pattern, all the objects must stand for the same expression. Thus f[x_,x_] can stand for f[2,2] but not f[2,3].
In a pattern object such as _h, the head h can be any expression, but cannot itself be a pattern.
A pattern object such as x__ stands for a sequence of expressions. So, for example, f[x__] can stand for f[a,b,c], with x being Sequence[a,b,c]. If you use x, say in the result of a transformation rule, the sequence will be spliced into the function in which x appears. Thus g[u,x,u] would become g[u,a,b,c,u].
When the pattern objects x_:v and x_. appear as arguments of functions, they represent arguments which may be omitted. When the argument corresponding to x_:v is omitted, x is taken to have value v. When the argument corresponding to x_. is omitted, x is taken to have a default value that is associated with the function in which it appears. You can specify this default value by making assignments for Default[f] and so on.

Default values.

A pattern like f[x__,y__,z__] can match an expression like f[a,b,c,d,e] with several different choices of x, y and z. The choices with x and y of minimum length are tried first. In general, when there are multiple __ or ___ in a single function, the case that is tried first takes all the __ and ___ to stand for sequences of minimum length, except the last one, which stands for "the rest" of the arguments.
When x_:v or x_. are present, the case that is tried first is the one in which none of them correspond to omitted arguments. Cases in which later arguments are dropped are tried next.

Attributes used in matching patterns.

Pattern objects like x_ can represent any sequence of arguments in a function f with attribute Flat. The value of x in this case is f applied to the sequence of arguments. If f has the attribute OneIdentity, then e is used instead of f[e] when x corresponds to a sequence of just one argument.