6.95 How to set up a function with optional arguments?

Optional arguments are very important and useful. It is easy to make these in Mathematica. lets say we want to make function foo that takes person name and age but the sex is provided as optional with default value as say male. To do this, two things are needed to be defined.

The function foo itself, but with additional argument called opt : OptionsPattern[{foo}] and we need to define an Options[foo] =... which sets up the default values. Here is an example

Clear["Global`*"]; 
 
(*this sets up the DEFAULT values for each optional argument *) 
Options[processPerson] = {"sex" -> "male"}; 
 
(*this is the definition of the function itself*) 
processPerson[name_String, age_?NumericQ, opt : OptionsPattern[{processPerson}]] /;  age > 0 := Module[{sexOfPerson}, 
 
  (* the following line reads the optional value sex->"" if provided *) 
  (* else Mathematica will automatically return the default value set up*) 
 
  sexOfPerson = OptionValue["sex"]; 
 
  Print["Name = ", name]; 
  Print["age = ", age]; 
  Print["sex = ", sexOfPerson] 
  ]
 

Now we are ready to call the function.

processPerson["me",10]
 

Gives

     Name = me 
     age = 10 
     sex = male

We see in the above, that variable sex was automatically set to the default value thanks to the definitions Options[foo]=...

Now we call it with explicitly passing in the optional argument

processPerson["me",10,"sex"->"female"]
 

Gives

    Name = me 
    age = me 
    sex = female

In the above, the option argument sex->"..." must always be the last one passed in. You can not do this for example

processPerson["joe doe","sex"->"female",10]
 

Here is another example

Clear["Global`*"]; 
Options[dsolve] = {"ic" -> {}, "hint" -> "None"}; 
dsolve[ode_, y_[x_], x_, OptionsPattern[]] :=  Module[{ic = OptionValue["ic"], hint = OptionValue["hint"]}, 
   Print["ic=", ic, " hint=", hint] 
   ]; 
 
dsolve[y''[x] + y[x] == 1, y[x], x, "ic" -> {x[0] == 1}] 
dsolve[y''[x] + y[x] == 1, y[x], x] 
dsolve[y''[x] + y[x] == 1, y[x], x, "hint" -> "linear",  "ic" -> {x[10] == 0}]
 

Which prints

ic={x[0]==1} hint="None" 
ic={} hint="None" 
ic={x[10]==0} hint="linear"

To find all options supported by function do as an example Options[LinearSolve] and that will print {Method -> Automatic, Modulus -> 0, ZeroTest -> Automatic}

It is better to use string for the name of the hint as in the above, so not to clash with the same symbol being already defined.