6
$\begingroup$

I have a very simple task, but for some reason I fail to accomplish it. I want to use Which to define a function. I think the code is self-explanatory:

In: f[x_, y_] := Which[x == en, 1, y == en, 2]

In: f[en, a]
Out: 1

OK, so far so good. But if other condition is satisfied, nothing happens:

In: f[a, en]
Out: Which[a == en, 1, en == en, 2]

I would expect to get 2 as output, not this. Why is this so?

I got same result if I use numbers instead of the symbolic expressions, and same result if I use Piecewise instead of Which.

Any ideas? Thanks!

$\endgroup$

1 Answer 1

8
$\begingroup$

In your case you should use === (SameQ) instead of == (Equal) in your definition.

The problem you are facing is caused by the fact that Equal (==) does not evaluate to True / False unless it has values to compare (see an illustrative example in the "Basic Examples" section of the documentation for SameQ).

f[x_, y_] := Which[x === en, 1, y === en, 2]

f[en, a] (* Out: 1 *)
f[a, en] (* Out: 2 *)

The same applies in the case of a Piecewise definition:

fp[x_, y_] := Piecewise[{{1, x === en}, {2, y === en}}]
fp[en, a] (* Out: 1 *)
fp[a, en] (* Out: 2 *)
$\endgroup$

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