Given that I have a function func
as follow:
To check the value of options, I using the step-by-step method If[]
Options[func] = {Method -> Automatic, WorkingPrecision -> MachinePrecision, Order->2};
func::badval = "`1` is not a valid value of option `2`";
func[arg1_,arg2_, opts : OptionsPattern[]] :=
Module[{method, prec, order},
method = Method /. {opts} /. Options[func];
prec= WorkingPrecision/. {opts} /. Options[func];
order= Order/. {opts} /. Options[func];
(*Check the value of the options*)
If[
! MemberQ[
{{"Euler", 2}, {"Midpoint", 2}, {"Heun", 2}, {"Heun", 3},
{"Kutta", 3}, {"RK", 4}, {"Gill", 4}, Automatic}, method],
Message[func::badval, method, Method]; Return[$Failed]];
If[
! (prec === MachinePrecision || NumericQ[prec]),
Message[func::badval, prec, WorkingPrecision]; Return[$Failed]];
If[
! (Head[order] ===Integer&& order >= 1),
Message[func::badval, order, Order]; Return[$Failed]];
(*main implementation*)
arg1 + arg2
]
Test
func[1, 2, WorkingPrecision -> MachinePrecisio, Order -> 1., Method -> Automati]
func::badval: Automati is not a valid value of option Method
However, I hope the warning information should like this or like the Plot
(see below)
func::badval: Automati is not a valid value of option Method
func::badval: MachinePrecisiois not a valid value of option WorkingPrecision
func::badval: 1.is not a valid value of option Order
The built-in throw the warning information
Plot[2 Sin[x] + x, {x, 0, 15},
PlotRange -> {a, c}, Filling -> bb,
Mesh -> pp, Axes -> Fals, WorkingPrecision -> MachinePrecisi]
General::prng: Value of option PlotRange -> {a,c} is not All, Full, Automatic, a positive machine number, or an appropriate list of range specifications.
Plot::wprec: Value of option WorkingPrecision -> MachinePrecisi is not a positive machine-sized real or integer. >>
Mesh::ilevels: pp is not a valid mesh specification. >>
Question
- How to check the value of options like the built-in functions, especially when the function have many options(the option number of
Plot
is60
)?
As said by Mr.Wizard in the comment, I hope that the func
executes the following operation:
(1) Multiple messages are issued
(2) Using default option values.
fail=False
, change theReturn[$Failed]
tofail=True
, after all checks, addIf[fail,Return[$Failed]]
. $\endgroup$ – ciao Jun 28 '15 at 7:01method/.{opts}/.Options[func]
overOptionValue[method]
? $\endgroup$ – Mr.Wizard Jun 28 '15 at 7:03Plot
example (1) multiple messages are issued and (2) the plot is still rendered using default option values. Are both these behaviors something you wish to duplicate? $\endgroup$ – Mr.Wizard Jun 28 '15 at 7:05OptionValue
is now the preferred method in most cases and I intend to use it where applicable. I suggest you read: (355) $\endgroup$ – Mr.Wizard Jun 28 '15 at 7:16