2

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[[1]] == l, lam = lam + 1, 
        list1[[1]] == 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[[1]] == l, lam = lam + 1, 
        list1[[1]] == lc, lam = lam - 1
  ]
]

I get

Which[lc == l, lam$538474 = lam$538474 + 1, 
      list1$538474[[1]] == lc, lam$538474 = lam$538474 - 1
]

Clearly something's wrong with the list1$538474[[1]] above. What am I missing?

rcollyer
  • 33,976
  • 7
  • 92
  • 191
H. Arponen
  • 123
  • 2

1 Answers1

5

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] *)
Brett Champion
  • 20,779
  • 2
  • 64
  • 121