Functions with Variable Numbers of Arguments

Unless f is a flat function, a pattern like 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 stands for a single Wolfram Language expression, a double blank such as stands for a sequence of one or more expressions.

Here stands for the sequence of expressions .
In[1]:=
Click for copyable input
Out[1]=
Here is a more complicated definition, which picks out pairs of duplicated elements in .
In[2]:=
Click for copyable input
The definition is applied twice, picking out the two paired elements.
In[3]:=
Click for copyable input
Out[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 , then typing in will lead to an infinite loop, with 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.

_any single expression
x_any single expression, to be named x
__any sequence of one or more expressions
x__sequence named x
x__hsequence of expressions, all of whose heads are h
___any sequence of zero or more expressions
x___sequence of zero or more expressions named x
x___hsequence of zero or more expressions, all of whose heads are h

More kinds of pattern objects.

Notice that with flat functions such as Plus and Times, the Wolfram Language automatically handles variable numbers of arguments, so you do not explicitly need to use double or triple blanks, as discussed in "Flat and Orderless Functions".

When you use multiple blanks, there are often several matches that are possible for a particular expression. By default, the Wolfram Language tries first those matches that assign the shortest sequences of arguments to the first multiple blanks that appear in the pattern. You can change this order by wrapping Longest or Shortest around parts of the pattern.

Longest[p]match the longest sequence consistent with the pattern p
Shortest[p]match the shortest sequence consistent with the pattern p

Controlling the order in which matches are tried.

This gives a list of all the matches that the Wolfram Language tries.
In[4]:=
Click for copyable input
Out[4]=
This forces the Wolfram Language to try the longest matches for x__ first.
In[5]:=
Click for copyable input
Out[5]=
Many kinds of enumeration can be done by using ReplaceList with various kinds of patterns.
In[6]:=
Click for copyable input
Out[6]=
This effectively enumerates all sublists with at least one element.
In[7]:=
Click for copyable input
Out[7]=
This tries the shortest matches for x__ first.
In[8]:=
Click for copyable input
Out[8]=