What's the best/canonical way to define a function with optional named arguments? To make it concrete, let's create a function foo
with named arguments a
, b
, and c
, which default to 1, 2, and 3, respectively. For comparison, here's a version of foo
with positional arguments:
foo[a_:1, b_:2, c_:3] := bar[a,b,c]
Here is sample input and output for the named-arguments version of foo
:
foo[] --> bar[1,2,3]
foo[b->7] --> bar[1,7,3]
foo[a->6, b->7, c->8] --> bar[6,7,8]
It should of course also be easy to have positional arguments before the named arguments.
I found the standard way to do it in the Mathematica documentation: http://reference.wolfram.com/mathematica/tutorial/SettingUpFunctionsWithOptionalArguments.html
Typing "OptionValue" every time is a little cumbersome. For some reason you can't just make a global abbreviation like
ov = OptionValue
but you can do this:Or this:
Or this:
I'll throw this possible solution into the mix:
I like it for its terseness but I don't think it's the standard way. Any gotchas with doing it that way?
PS, it uses the following handy utility function:
Yes,
OptionValue
can be a bit tricky because is relies on a piece of magic so thatThrowing in an explicit
Automatic
usually does the trick, so in your case I would say that the solution is:By the way, options used to be done by matching to
opts:___?OptionQ
, and then finding option values manually as{a,b,c}/.Flatten[{opts}]
. The pattern checkOptionQ
is still around (although not documented), but theOptionValue
approach has the advantage that you get warnings for non-existing options (e.g.foo[d->3]
). This would also be the case for your second response, but not for the one you have accepted.