# How to specify optional string parameters in a function signature and identify the pattern

As a newbie, I've got a rather simple question.

I would like to define a function that accepts one of a few possible strings.

I.e., I wish to do the following.

f[s_"a"|"b"] := do something useful with s


But of course that syntax doesn't work. Note that the function definition is not overloaded.

I achieved this the following way.

f[key2_ /; MemberQ[Map[StringMatchQ[key2, #] &, {"Cat", "Bird", "Mouse"}], True]] := someAssoc["Key1"][key2]


Is there a better way to express this?

You can use Pattern:

f[s : "a" | "b"] := s <> ": stuff"
f /@ {"a", "b", "c", 2}


{"a: stuff", "b: stuff", f["c"], f[2]}

• Great thanks. As I suspected, the language has an affordance. – CalvinDale Aug 25 '18 at 22:13
• @CalvinDale, my pleasure. Thank you for the accept. – kglr Aug 25 '18 at 22:15