WolframLang: Define Function with Optional Parameters

By Xah Lee. Date: . Last updated: .

There are 2 main ways to define function with optional parameters.

Optional Positional Parameters

The optional positional parameters come after required parameters. When not given, default values are used.

typically, you define them like this:

f[ args, name1_:val1, name2_:val2, etc] := body;

Clear[ f ];
f[a_, b_:3] := {a, b} ;

(* second arg is not given. default to 3. *)
f[x]
(* {x, 3} *)

f[x,y]
(* {x, y} *)
Clear[ f ];

(* defining a function with more than one optional positional parameters *)

f[a_, b_:3, c_:4] := {a, b, c} ;

f[x]
(* {x, 3, 4} *)

f[x,y]
(* {x, y, 4} *)

f[x,y,z]
(* {x, y, z} *)

Optional Named Parameters

To define a function with optional named parameters:

Define the optional parameters and their default values like this:

Options[ fname ] = { name1 -> defaultVal1, name2 -> defaultVal2, etc };

Then, put OptionsPattern[] as the last parameter. e.g.

f[a_, OptionsPattern[]] := body

In function body, use OptionValue[name] to get the value.

Clear[ f ];

(* defining a function with optional named parameters *)

(* define the named parameters and their default values *)
Options[ f ] = {aa -> 3, bb -> 4};

f[a_, OptionsPattern[  ]] := {a, OptionValue[ aa ], OptionValue[ bb ]} ;

f[x]
(* {x, 3, 4} *)

f[x, aa -> 99 ]
(* {x, 99, 4} *)

f[x, bb -> 88 ]
(* {x, 3, 88} *)

f[x, aa -> 99, bb -> 88 ]
(* {x, 99, 88} *)

WolframLang, Define Function