Optional and Default Arguments

Sometimes you may want to set up functions where certain arguments, if omitted, are given "default values". The pattern stands for an object that can be omitted, and if so, will be replaced by the default value v.

This defines a function with a required argument , and optional arguments and , with default values and , respectively.
In[1]:=
Click for copyable input
The default value of is used here.
In[2]:=
Click for copyable input
Out[2]=
Now the default values of both and are used.
In[3]:=
Click for copyable input
Out[3]=
x_:van expression which, if omitted, is taken to have default value v
x_h:van expression with head h and default value v
x_.an expression with a built-in default value

Pattern objects with default values.

Some common Mathematica functions have built-in default values for their arguments. In such cases, you need not explicitly give the default value in , but instead you can use the more convenient notation in which a built-in default value is assumed.

x_+y_.default for is
x_y_.default for is
x_^y_.default for is

Some patterns with optional pieces.

Here matches the pattern with taken to have the default value .
In[4]:=
Click for copyable input
Out[4]=

Because Plus is a flat function, a pattern such as can match a sum with any number of terms. This pattern cannot, however, match a single term such as . However, the pattern contains an optional piece, and can match either an explicit sum of terms in which both and appear, or a single term , with taken to be .

Using constructs such as , you can easily construct single patterns that match expressions with several different structures. This is particularly useful when you want to match several mathematically equal forms that do not have the same structure.

The pattern matches , but not .
In[5]:=
Click for copyable input
Out[5]=
By giving a pattern in which the exponent is optional, you can match both cases.
In[6]:=
Click for copyable input
Out[6]=
The pattern matches any linear function of .
In[7]:=
Click for copyable input
In this case, .
In[8]:=
Click for copyable input
Out[8]=
Here and .
In[9]:=
Click for copyable input
Out[9]=

Standard Mathematica functions such as Plus and Times have built-in default values for their arguments. You can also set up defaults for your own functions, as described in "Patterns".

Sometimes it is convenient not to assign a default value to an optional argument; such arguments can be specified with the help of PatternSequence[].

p|PatternSequence[]optional pattern p with no default value

Optional argument without a default value.

The pattern matches an optional second argument of , without a default value.
In[10]:=
Click for copyable input
Out[10]=
New to Mathematica? Find your learning path »
Have a question? Ask support »