8
$\begingroup$

Consider the two seemingly closely related operations:

DeleteCases[{f[x], g[x], h[x]}, x_[_] /; x == f]
(* {g[x], h[x]} *)    
DeleteCases[{f[x], g[x], h[x]}, x_[_] /; x != f]
(* {f[x], g[x], h[x]} *)    

The first case gives the desired result of removing f[x], while the second doesn't work properly (I would expect to get back only f[x] in that case). However, the only difference between the two is the use of a != as opposed to a ==. Is this a bug or is there a good reason for this behavior?

Note: Interestingly, even Not[Equal[x,f]] doesn't fix the problem (while Equal[x,f] does work).

$\endgroup$
2
  • 1
    $\begingroup$ Not sure quite what is going (I'm pretty sure it's relatively straight-forward), but consider doing the following: DeleteCases[{f[x], g[x], h[x]}, x_[_] /; (x =!= f)]. Also, DeleteCases[{f[x], g[x], h[x]}, _f] and Cases[{f[x], g[x], h[x]}, _f]. $\endgroup$
    – march
    Commented Mar 12, 2016 at 3:43
  • 4
    $\begingroup$ For comparisons like yours, you really should be using ===/=!= instead of ==/!=. $\endgroup$ Commented Mar 12, 2016 at 3:57

2 Answers 2

10
$\begingroup$

Even Equal doesn't work, although it seems to work. What you expect is a comparison, that gives True when two symbols are the same and False otherwise. Look at this:

f == g
(* f == g *)

This is surely not what you expect. While it seems OK in your first example, because f==f indeed simplifies to True, the flaw becomes obvious in your second example:

g != f
(* g != f *)

Mathematica tries to decide whether f and g are unequal. The problem is that unequal is not equivalent to they are not the same. So the rule of thumb is, if you do numeric comparisons, then you often want to use == or != except you are comparing exact numbers. If you want to decide whether expressions are the same or not, then you need to use === or =!=.

Here are some examples as a brain teaser:

1 === 1.0
(* False *)

1 == 1.0
(* True *)
$\endgroup$
2
$\begingroup$

Something "ugly" also:

DeleteCases[{f[x], g[x], h[x]}, x_[_] /; TrueQ[x == f]]

(*{g[x], h[x]}*)

DeleteCases[{f[x], g[x], h[x]}, x_[_] /; !TrueQ[x == f]]

(*{f[x]}*)
$\endgroup$

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