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

Documentation / Mathematica / The Mathematica Book / Principles of Mathematica / Patterns /

2.3.8 Functions with Variable Numbers of Arguments

Unless f is a flat function, a pattern like f[x_, y_] stands only for instances of the function with exactly two arguments. Sometimes you need to set up patterns that can allow any number of arguments.

You can do this using multiple blanks. While a single blank such as x_ stands for a single Mathematica expression, a double blank such as x__ stands for a sequence of one or more expressions.

Here x__ stands for the sequence of expressions (a, b, c).

In[1]:= f[a, b, c] /. f[x__] -> p[x, x, x]


Here is a more complicated definition, which picks out pairs of duplicated elements in h.

In[2]:= h[a___, x_, b___, x_, c___] := hh[x] h[a, b, c]

The definition is applied twice, picking out the two paired elements.

In[3]:= h[2, 3, 2, 4, 5, 3]


"Double blanks" __ stand for sequences of one or more expressions. "Triple blanks" ___ stand for sequences of zero or more expressions. You should be very careful whenever you use triple blank patterns. It is easy to make a mistake that can lead to an infinite loop. For example, if you define p[x_, y___] := p[x] q[y], then typing in p[a] will lead to an infinite loop, with y repeatedly matching a sequence with zero elements. Unless you are sure you want to include the case of zero elements, you should always use double blanks rather than triple blanks.

More kinds of pattern objects.

Notice that with flat functions such as Plus and Times, Mathematica automatically handles variable numbers of arguments, so you do not explicitly need to use double or triple blanks, as discussed in Section 2.3.7.

When you use multiple blanks, there are often several matches that are possible for a particular expression. In general, Mathematica tries first those matches that assign the shortest sequences of arguments to the first multiple blanks that appear in the pattern.

This gives a list of all the matches that Mathematica tries.

In[4]:= ReplaceList[f[a, b, c, d], f[x__, y__] -> g[{x}, {y}]]


Many kinds of enumeration can be done by using ReplaceList with various kinds of patterns.

In[5]:= ReplaceList[f[a, b, c, d], f[___, x__] -> g[x]]


This effectively enumerates all sublists with at least one element.

In[6]:= ReplaceList[f[a, b, c, d], f[___, x__, ___] -> g[x]]