MATHEMATICA TUTORIAL

Repeated Patterns

expr..a pattern or other expression repeated one or more times
expr...a pattern or other expression repeated zero or more times

Repeated patterns.

Multiple blanks such as allow you to give patterns in which sequences of arbitrary expressions can occur. The Mathematica pattern repetition operators and allow you to construct patterns in which particular forms can be repeated any number of times. Thus, for example, represents any expression of the form , , , and so on.

The pattern allows the argument to be repeated any number of times.
In[1]:=
Click for copyable input
Out[1]=
This pattern allows any number of arguments, followed by any number of arguments.
In[2]:=
Click for copyable input
Out[2]=
Here each argument can be either or .
In[3]:=
Click for copyable input
Out[3]=

You can use and to represent repetitions of any pattern. If the pattern contains named parts, then each instance of these parts must be identical.

This defines a function whose argument must consist of a list of pairs.
In[4]:=
Click for copyable input
The definition applies in this case.
In[5]:=
Click for copyable input
Out[5]=
With this definition, the second elements of all the pairs must be the same.
In[6]:=
Click for copyable input
The definition applies in this case.
In[7]:=
Click for copyable input
Out[7]=

The pattern x.. can be extended to two arguments to control the number of repetitions more precisely.

p.. or Repeated[p]a pattern or other expression repeated one or more times
Repeated[p,max]a pattern repeated up to max times
Repeated[p,{min,max}]a pattern repeated between min and max times
Repeated[p,{n}]a pattern repeated exactly n times

Controlling the number of repetitions.

This finds from two to three repetitions of the argument a.
In[8]:=
Click for copyable input
Out[8]=
New to Mathematica? Find your learning path »
Have a question? Ask support »