I want to define a function whose arguments or options can only be selected in a range. For example:

TestFunction[x_, opts:OptionsPattern[]]:=Module[{},...];

Here, the problemID must one value of {1, 2, 3, 4}, and the default value is 1.

My question is how to define such argument or options. For example, that is the argument like the second argument of build-in function Import[], whose second argument can only be selected in {Element, Data, List, CSV, .... and so on}. Or that is the option "ImageSize" of built-in Plot function.

Thank you very much!


2 Answers 2

Options[testFunc] = {opt -> 1};
testFunc[x_, OptionsPattern[]] := x^2 /; Range[4]~MemberQ~OptionValue[opt];
testFunc[x_, OptionsPattern[]] := "option provided out of range"

testFunc[50, opt -> 2]
(* 2500 *)

testFunc[50, opt -> 5]
(* option provided out of range *)
  • 2
    $\begingroup$ You could simplify this slightly by removing the condition from your second, "default" definition for incorrect options: the first will only match the admissible values, the second will then match everything else. You also don't need to assign a label to OptionsPattern in this case since you don't refer to it in the function definitions. (+1) $\endgroup$
    – MarcoB
    Commented Jul 10, 2017 at 14:39
  • $\begingroup$ @MarcoB thanks for the feedback. please feel free to edit ! $\endgroup$
    – Ali Hashmi
    Commented Jul 10, 2017 at 15:09

Another possibilty would be to use the option default value if the test fails

Options[fun] = {op1 -> 1, op2 -> 2};

fun[x_, OptionsPattern[]] :=
  Module[{o = OptionValue[op1], v},
   v = If[MemberQ[Range@4, o], o, op1 /. Options[fun]];
   x + v];

fun[1, op1 -> 6, op2 -> 67]


fun[6, op1 -> 6, op2 -> 67]



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.