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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)