1.7. Optional and Keyword Arguments to Functions#
1.7.1. Optional arguments#
Arguments to a function can be made optional by providing a default value. This simplifies the calling syntax when the default value is desired, but still allows for overriding if needed.
As an example, consider solving the equation \(2x=\tan x\) using the fixed-point iteration \(x_{n+1} = \tan^{-1}(2x_n)\). Our arguments are the termination tolerance \(\delta\) (that is, the iterations will continue until \(|x_{n+1}-x_n|\le \delta\)) and the starting value \(x_0\). In the function below, these arguments have default values of \(10^{-3}\) and \(1.0\), resepectively.
function fixpnt(δ=1e-3, x0=1.0)
x = x0
iter = 0
while true
iter += 1
x0 = x
x = atan(2x0)
if abs(x-x0) ≤ δ
println("Terminating after $iter iterations, x = $x")
return
end
end
end
fixpnt (generic function with 3 methods)
The function can now called with no arguments, meaning the default values are used for δ
and x0
:
fixpnt()
Terminating after 6 iterations, x = 1.165380637446075
If we provide one argument, it will override the default value for δ
but use the default value for x0
:
fixpnt(1e-10)
Terminating after 20 iterations, x = 1.165561185193013
Finally, if both arguments are provided, none of the default values will be used:
fixpnt(1e-10, 0.1)
Terminating after 24 iterations, x = 1.1655611851826804
Note that it is not possible to use the default value for the first argument δ
, but overriding the second argument x0
. The next topic will show how to use so-called keyword arguments for this.
1.7.2. Keyword arguments#
Functions with keyword arguments are defined using a semicolon in the signature. These arguments have to be provided using their names when called, however, the order can be arbitrary. As before, default values can also be provided for keyword arguments.
As an example, we add a named argument maxiter
to the previous example:
function fixpnt2(δ=1e-3, x0=1.0; maxiter=10)
x = x0
iter = 0
while true
iter += 1
x0 = x
x = atan(2x0)
if iter ≥ maxiter || abs(x-x0) ≤ δ
println("Terminating after $iter iterations, x = $x")
return
end
end
end
fixpnt2 (generic function with 3 methods)
We can now for example provide the first argument δ
, use the default value for the second argument x0
, but specify the keyword argument maxiter
as follows:
fixpnt2(1e-10, maxiter=15)
Terminating after 15 iterations, x = 1.165561180314663