0
$\begingroup$

I have

a["tree"] := "oak"
a["flower"] := "rose"
a["dog" | "cat"] := "animals"

I want that the last definition of a behaves differently like in

b[x_ /; x == "dog" || x == "cat"] := If[x == "dog", "wow", "miau"]

but want to do this with a

Is there a way to write something like

a["dog" | "cat"] := If[ (* passed parameter *) == "dog", "wow", "miau"]
$\endgroup$
3
  • 2
    $\begingroup$ Like a[x : "dog" | "cat"] := Switch[x, "dog", 1, "cat", 2]? P.s. there is not need for := in first two cases. $\endgroup$
    – Kuba
    Commented Jun 6, 2014 at 10:53
  • $\begingroup$ @Kuba - That's exactly what I was looking for and couldn't find. Thank you very much. $\endgroup$
    – eldo
    Commented Jun 6, 2014 at 10:57
  • $\begingroup$ You should avoid Switch if possible; please read this: (2618) $\endgroup$
    – Mr.Wizard
    Commented Jun 6, 2014 at 10:58

1 Answer 1

2
$\begingroup$

The clearest and fastest (execution time) method is to simply use two definitions:

a["dog"] = "wow";
a["cat"] = "miau";

On reflection this is so straightforward that I doubt I understand your question or the reason behind it. Could you give another example, please?

A related question:

$\endgroup$
6
  • $\begingroup$ The reason behind my question was that I thought I could keep a long story short by using Alternatives. I agree that a Swift makes it long again, but would not say at this point that Kuba's comment is without advantages in some cases. $\endgroup$
    – eldo
    Commented Jun 6, 2014 at 11:11
  • $\begingroup$ @eldo Could you give an example where you feel that multiple definitions is clumsy? Perhaps I can recommend a way to improve it. For the existing example I strongly recommend this method over Switch for both performance and clarity. $\endgroup$
    – Mr.Wizard
    Commented Jun 6, 2014 at 11:14
  • $\begingroup$ @eldo you can make it more compact if you need: alt = {"dog", "cat"}; val = {1, 2}; ClearAll[a]; MapThread[Set, {a /@ alt, val}]; $\endgroup$
    – Kuba
    Commented Jun 6, 2014 at 11:14
  • $\begingroup$ @Kuba You can even enter values as a 2D table a la Piecewise, if this is a matter of visual formatting. (Assuming use of the Notebook interface.) $\endgroup$
    – Mr.Wizard
    Commented Jun 6, 2014 at 11:18
  • $\begingroup$ @Mr.Wizard - Reading "2618", I would recommend to myself your second ansatz ( g[2] = 28 ... ) because of its clarity. In a certain sense my question was a duplicate. You should add that link to your answer. $\endgroup$
    – eldo
    Commented Jun 6, 2014 at 11:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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