Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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"]
share|improve this question
2  
Like a[x : "dog" | "cat"] := Switch[x, "dog", 1, "cat", 2]? P.s. there is not need for := in first two cases. –  Kuba Jun 6 at 10:53
    
@Kuba - That's exactly what I was looking for and couldn't find. Thank you very much. –  eldo Jun 6 at 10:57
    
You should avoid Switch if possible; please read this: (2618) –  Mr.Wizard Jun 6 at 10:58

1 Answer 1

up vote 2 down vote accepted

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:

share|improve this answer
    
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 6 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 6 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 6 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 6 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 6 at 11:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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