2
$\begingroup$

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?

$\endgroup$
3
$\begingroup$

You can use Pattern:

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

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

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

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.