I have a user-defined function, func
, which takes the following form:
func[arg1, arg2, options]
Here is the actual code
Options[func] =
{opt1 -> Automatic, opt2 -> False, opt3 -> {1, 0, 0},
opt4 -> {0, 0, 0}};
func::invarg1 = "`1` should be a numerical array construction with dimention 2.";
func::invarg2 = "`1` should be a postive value.";
func::invopt1 =
"Value of option opt1 \[Rule] `1` should be a valid value like Automatic or deCasteljau.";
func::invopt2 =
"Value of option opt2 \[Rule] `1` should be a valid boolean value like True or False.";
func::invopt3 =
"Value of option opt3 \[Rule] `1` should be a non-negative machine-sized
number list of length 3.";
func::invopt4 =
"Value of option opt4 \[Rule] `1` should be a non-negative machine-sized
number list of length 3.";
SyntaxInformation[func] = {"ArgumentsPattern" -> {_, _, OptionsPattern[]}};
func[arg1_, arg2_, opts : OptionsPattern[]] /;
MatrixQ[arg1, NumericQ] && arg2 > 0 :=
Module[{o1, o2, o3, o4},
o1 = OptionValue[opt1];
o2 = OptionValue[opt2];
o3 = OptionValue[opt3];
o4 = OptionValue[opt4];
If[! MemberQ[{Automatic, "deCasteljau"}, o1],
Message[func::invopt1, o1];
Return[$Failed]
];
If[! MemberQ[{True, False}, o2],
Message[func::invopt2, o2];
Return[$Failed]
];
If[! (VectorQ[o3, NumericQ] && Length@o3 == 3),
Message[func::invopt3, o3];
Return[$Failed]
];
If[! (VectorQ[o4, NumericQ] && Length@o4 == 3),
Message[func::invopt4, o4];
Return[$Failed]
];
(*continue to do something*)
{arg1, arg2, o1, o2, o3, o4}
]
For the arguments arg1,arg2
, a better checking is via the side-effect, rather than If[]
statement.
func[arg1_ /; ! MatrixQ[arg1, NumericQ], arg2_, opts : OptionsPattern[]] /;
(Message[func::invarg1, arg1]; False) := $Failed
func[arg1_, arg2_ /; arg2 <= 0, opts : OptionsPattern[]] /;
(Message[func::invarg2, arg2]; False) := $Failed
In implementation of func
, I use If
to check the validity of the options step by step. Nevertheless, I believe this is not an ideal solution in Mathematica, especially when a function has many ($30$ or more) options.
So I would like to know:
- Which method is ideaL/better to deal with the vality of options?