# Rookie mistake in defining a function with Modules?

I can't figure out what's wrong with this piece of code. I'm trying to define a function that counts the occurrences of x, y and l or lc in expressions like x[x[y[l]], where x will add 1 to an "eigenvalue", y will subtract 1 and likewise for l and lc. Then for example I would get H[x[x[y[l]]] = 2. Now I'm stuck at the first phase with the function defined below:

H[z_] := Module[{list1 = Join[Level[z, Infinity], {z}], lam = 0},
Which[list1[] == l, lam = lam + 1,
list1[] == lc, lam = lam - 1
];
lam
]


This should give H[l] = 1 and H[lc] = -1, but instead I get just the initial value lam = 0 for the "lc" case... When I discard the last line and use instead

H[z_] := Module[{list1 = Join[Level[z, Infinity], {z}], lam = 0},
Which[list1[] == l, lam = lam + 1,
list1[] == lc, lam = lam - 1
]
]


I get

Which[lc == l, lam$538474 = lam$538474 + 1,
list1$538474[] == lc, lam$538474 = lam$538474 - 1 ]  Clearly something's wrong with the list1$538474[] above. What am I missing?

• I quit and restarted the kernel and nothing!! This is beginning to seem really strange... – H. Arponen Jan 16 '13 at 19:40
• What do you mean by "nothing"? No change? No output? – Sjoerd C. de Vries Jan 16 '13 at 19:41
• Still gives H[lc]=0... – H. Arponen Jan 16 '13 at 19:41

## 1 Answer

Use SameQ (===) instead of Equal (==). Equal of two symbols will return unevaluated (so neither True nor False) causing Which to return unevaluated:

If any of the $test_i$ evaluated by Which give neither True nor False, then a Which object containing these remaining elements is returned unevaluated.

Which[foo == foo, 1, foo == bar, 2]

(* ==> 1 *)

Which[foo == bar, 1, foo == foo, 2]

(* ==> Which[foo == bar, 1, foo == foo, 2] *)

• 5 secs too late... – Sjoerd C. de Vries Jan 16 '13 at 19:54
• He could also use TrueQ[foo==bar] – Mike Honeychurch Jan 16 '13 at 21:15
• @MikeHoneychurch True, although that requires more typing. :-) – Brett Champion Jan 16 '13 at 21:30
• sure does. exhausting :) . Was just wanting to cover all the bases in any case. – Mike Honeychurch Jan 16 '13 at 21:31
• That works great, thanks Brett!! :) – H. Arponen Jan 17 '13 at 7:26