###Two common examples
Complex numbers
An example of this that shows up quite often is when matching expressions with complex numbers. Some common examples are the following:
Cases[-I, I, Infinity]
(* { } *)
Cases[2 I, I, Infinity]
(* { } *)
The reason why I
appears nowhere in those expressions is revealed when we look at the FullForm
of the expressions:
I // FullForm
(* Complex[0, 1] *)
-I // FullForm
(* Complex[0, -1] *)
1 + 2 I // FullForm
(* Complex[1, 2] *)
All of these expressions are atoms; that is, they are all considered indivisible (structureless) objects in Mathematica (at least as far as pattern-matching is concerned).
Different fixes are useful for different use cases, of course. If one wants to manually conjugate a symbolic expression, one can do
expr /. z_Complex :> Conjugate[z]
If one wants to treat I
as a symbol rather than as a complex number, one can do
Clear@i
expr /. Complex[a_, b_] :> a + i b
The moral is as above: it is often useful to look at the FullForm
of an expression in order to design patterns for matching subexpressions.
Powers in the denominator
Consider the following:
The reason that the denominator gets replaced in the second case but not the first is revealed by looking at the FullForm
s of the expressions:
In the first case, the expression is internally represented with a negative power, but it is displayed as being the denominator of a fraction. Thus, the pattern _^2
is not matched, and so the expression is not replaced.