2
$\begingroup$

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?

$\endgroup$
3
  • $\begingroup$ I quit and restarted the kernel and nothing!! This is beginning to seem really strange... $\endgroup$
    – H. Arponen
    Commented Jan 16, 2013 at 19:40
  • $\begingroup$ What do you mean by "nothing"? No change? No output? $\endgroup$ Commented Jan 16, 2013 at 19:41
  • $\begingroup$ Still gives H[lc]=0... $\endgroup$
    – H. Arponen
    Commented Jan 16, 2013 at 19:41

1 Answer 1

5
$\begingroup$

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] *)
$\endgroup$
5
  • $\begingroup$ 5 secs too late... $\endgroup$ Commented Jan 16, 2013 at 19:54
  • $\begingroup$ He could also use TrueQ[foo==bar] $\endgroup$ Commented Jan 16, 2013 at 21:15
  • $\begingroup$ @MikeHoneychurch True, although that requires more typing. :-) $\endgroup$ Commented Jan 16, 2013 at 21:30
  • $\begingroup$ sure does. exhausting :) . Was just wanting to cover all the bases in any case. $\endgroup$ Commented Jan 16, 2013 at 21:31
  • $\begingroup$ That works great, thanks Brett!! :) $\endgroup$
    – H. Arponen
    Commented Jan 17, 2013 at 7:26

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.