2
$\begingroup$

Is there a way to force only selected values for function argument? For example for this function:

g[x_, y_, a_: ("b" || "c")] := Print[x, y, a]

force a to only get either values "b" or "c".

$\endgroup$
4
  • 2
    $\begingroup$ One way would be g[x_, y_, a_] /; MemberQ[{"b", "c"}, a] := Print[x, y, a]. $\endgroup$ Aug 18 at 10:17
  • 2
    $\begingroup$ ClearAll[g]; g[x_, y_, a : "b" | "c"] := Print[x, y, a] ? $\endgroup$
    – kglr
    Aug 18 at 10:20
  • $\begingroup$ Thank you, @kglr and b.gates.you.know.what. Both answers worked. It's strange that I've tried kglr's answer multiple times before posting this question, but for some reason it failed to work properly. $\endgroup$
    – Tigran
    Aug 18 at 10:44
  • $\begingroup$ At least closely related: 132037 $\endgroup$
    – Kuba
    Aug 18 at 12:33
2
$\begingroup$

Both answers of @kglr :

ClearAll[g]; g[x_, y_, a : "b" | "c"] := Print[x, y, a]

and @b.gates.you.know.what :

g[x_, y_, a_] /; MemberQ[{"b", "c"}, a] := Print[x, y, a]

worked.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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