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

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?




1 Answer
1



You can use Pattern:


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 at 22:13





@CalvinDale, my pleasure. Thank you for the accept.
– kglr
Aug 25 at 22:15






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.