WolframLang: Define Function with Optional Parameters

By Xah Lee. Date: . Last updated: .

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

Define Function with Optional Positional Parameters

The optional 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} *)

Define Function with 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[]] := right-hand-side

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 ] = {abc -> 3, xyz -> 4};

f[a_, OptionsPattern[  ]] := {a, OptionValue[ abc ], OptionValue[ xyz ]} ;

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

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

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

f[x, abc -> 99, xyz -> 88 ]
(* {x, 99, 88} *)

WolframLang: Define Function