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

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

2.3.9 Optional and Default Arguments

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

This defines a function j with a required argument x, and optional arguments y and z, with default values 1 and 2, respectively.

In[1]:= j[x_, y_:1, z_:2] := jp[x, y, z]

The default value of z is used here.

In[2]:= j[a, b]

Out[2]=

Now the default values of both y and z are used.

In[3]:= j[a]

Out[3]=

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 x_:v, but instead you can use the more convenient notation x_. in which a built-in default value is assumed.

Some patterns with optional pieces.

Here a matches the pattern x_ + y_. with y taken to have the default value 0.

In[4]:= {f[a], f[a + b]} /. f[x_ + y_.] -> p[x, y]

Out[4]=

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

Using constructs such as x_., 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 g[a^2], but not g[a + b].

In[5]:= {g[a^2], g[a + b]} /. g[x_^n_] -> p[x, n]

Out[5]=

By giving a pattern in which the exponent is optional, you can match both cases.

In[6]:= {g[a^2], g[a + b]} /. g[x_^n_.] -> p[x, n]

Out[6]=

The pattern a_. + b_. x_ matches any linear function of x_.

In[7]:= lin[a_. + b_. x_, x_] := p[a, b]

In this case, b 1.

In[8]:= lin[1 + x, x]

Out[8]=

Here b 1 and a 0.

In[9]:= lin[y, y]

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 Section A.5.1.