Consider the following piece of code:
Options[f] = {Option -> True};
f[x_, OptionsPattern[]] := Module[{option},
option = OptionValue@Option;
If[option, x + 1, x]
]
f[4, {{}, {}}, Option -> True, {}, {}]
f[4, {{}}, {}, {}]
f[4]
5
5
5
Why does the function f
ignore that empty lists and returns the same output as without them instead of returning the same input ? How this behaviour can be avoided ?
Answer
Why does the function f ignore that empty lists ...
This is because options can be given in a list, so they can easily be stored and passed around.
opts = {PlotRange -> {-2, 2}, PlotStyle -> Red};
Plot[Sin[x] + Sin[1.4 x], {x, 0, 10}, Evaluate[opts]]
From OptionsPattern
:
OptionsPattern
matches any sequence or nested list of rules, specified with->
or:>
.
Thus an empty list will match, and it is equivalent to giving no options.
How this behaviour can be avoided ?
The best answer really depends on why you want to avoid this, so I am going to stop here. This behaviour is generally preferable. It may be inconvenient when you want to allow both options and optional arguments.
Comments
Post a Comment