0

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"]
eldo
  • 67,911
  • 5
  • 60
  • 168

1 Answers1

2

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:

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • 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. – eldo Jun 06 '14 at 11:11
  • @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. – Mr.Wizard Jun 06 '14 at 11:14
  • @eldo you can make it more compact if you need: alt = {"dog", "cat"}; val = {1, 2}; ClearAll[a]; MapThread[Set, {a /@ alt, val}]; – Kuba Jun 06 '14 at 11:14
  • @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.) – Mr.Wizard Jun 06 '14 at 11:18
  • @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. – eldo Jun 06 '14 at 11:40
  • @eldo Link added as requested. – Mr.Wizard Jun 06 '14 at 11:45