I have two functions with options, for example f
and g
ClearAll[f,g,h]
h::ioppf = "Value of option MaxIterations should be a positive integer.";
g::method = "The Method option should be \"one\" or \"two\".";
h::fun = "The fun option should be \"f\" or \"g\".";
f[x_, opts : OptionsPattern[MaxIterations -> 5]] :=
ConstantArray[x, OptionValue[MaxIterations]] /;
If[OptionValue[MaxIterations] > 0, True, Message[h::ioppf]; False]
g[x_, opts : OptionsPattern[{Method -> "one", MaxIterations -> 5}]] :=
ConstantArray[
OptionValue[Method] /.{"one" -> Sqrt[x], "two" -> x^2},
OptionValue[MaxIterations]
] /;
If[MemberQ[{"one","two"},OptionValue[Method]], True, Message[g::method]; False] &&
If[OptionValue[MaxIterations] > 0, True, Message[h::ioppf]; False]
In function h
we can select which function (f
or g
) we want to use (option fun
)
h[x_, opts : OptionsPattern[{fun -> "f", Method->"one", MaxIterations->3}]]:=
Module[{func, arg},
FilterRules[{opts},Options[h]];
func = ToExpression@OptionValue[fun];
arg = OptionValue[fun]/.
{"f" -> Join[{x}, {MaxIterations -> OptionValue[MaxIterations]}],
"g" -> Join[{x}, {Method -> OptionValue[Method],
MaxIterations -> OptionValue[MaxIterations]}]};
func@@arg
]/;
If[MemberQ[{"f","g"}, OptionValue[fun]], True, Message[h::fun]; False] &&
If[OptionValue[MaxIterations] > 0, True, Message[h::ioppf]; False] &&
If[MemberQ[{"one","two"}, OptionValue[Method]], True, Message[g::method]; False]
Examples:
h[x] (* {x,x,x} *)
h[x,fun->"f"] (* {x,x,x} *)
h[x,fun->"g"] (* {Sqrt[x],Sqrt[x],Sqrt[x]} *)
h[x,fun->"g",Method->"two"] (* {x^2,x^2,x^2} *)
h[x,fun->"g",MaxIterations->5] (* {Sqrt[x],Sqrt[x],Sqrt[x],Sqrt[x],Sqrt[x]} *)
h[x,fun->"g",Method->"two",MaxIterations->5] (* {x^2,x^2,x^2,x^2,x^2} *)
with messages:
h[x,fun->"u"]
h[x,fun->"f",MaxIterations->0]
h[x,fun->"g",Method->"2"]
That's what I need. But I want to make the input form with particular options:
h[x, fun->"f"] (* { x,x,x} *)
h[x, fun->{"f", MaxIterations->10}] (* {x,x,x,x,x,x,x,x,x,x} *)
h[x, fun->{"g", Method->"one", MaxIterations->10}]
(*
{Sqrt[x],Sqrt[x],Sqrt[x],Sqrt[x],Sqrt[x],Sqrt[x],Sqrt[x],Sqrt[x],Sqrt[x],Sqrt[x]} *)
How to call these functions with particular options?
And can you suggest me more elegant way to write h
function? Maybe I can use Check
instead of If
?