# How to define an option or an argument whose values are confined

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

Options[TestFunction]={problemID->1};
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!

• – jkuczm Jul 10 '17 at 21:30

ClearAll[testFunc];
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 *)

• 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) – MarcoB Jul 10 '17 at 14:39
• @MarcoB thanks for the feedback. please feel free to edit ! – Ali Hashmi Jul 10 '17 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]


2

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


7