Skip to main content

programming - Dealing with nested options


OptionValue allows for recent versions of Mathematica (I think as from 7) to easily access optional parameters if they are explicitely given to a function or their default values otherwise.


For big functions using options of options can be useful but we don't have in such cases something like OptionValue in order to access them. We must resort to using Replace in order to use them.


See for example the option "LegendGridOptions" in the answer of Jens to the question Creating legends for plots with multiple lines?


"LegendGridOptions" -> {Alignment -> Left, Spacings -> {.4, .1}}}

Has someone already tried to do something like OptionValue for sub-options ?



Answer



You can actually use OptionValue to extract options of options by doing something like OptionValue[option -> subOption]. For example



Options[ff] = {"fruit" -> {apple -> 1, pear -> 2, orange -> 3}}
ff[OptionsPattern[]] := {apple, OptionValue["fruit" -> apple]}

ff["fruit" -> {apple -> 4}]

(* ==> {apple, 4} *)

Comments