I think this may be what ilian is driving at, but I couldn't be sure in first answer. I thought that some elaboration would be helpful in any case. The behavior of flat and orderless functions in patterns is explained in tutorial/FlatAndOrderlessFunctions
. While Orderless
is significant here, I think it is the attribute Flat
that one needs pay particular attention to.
Consider these examples:
2 x y /. {2 x -> a, 2 x y -> b}
(* a y *)
2 x y /. {x -> a, 2 x y -> b}
(* b *)
When we look at the FullForm
, it is important to pay attention not just to 2 x y
, but to the patterns that are potential matches, 2 x
, 2 x y
and x
.
ReplaceAll[
Times[2, x, y],
List[
Rule[Times[2, x], a],
Rule[Times[2, x, y], b]]]
ReplaceAll[
Times[2, x, y],
List[
Rule[x, a],
Rule[Times[2, x, y], b]]]
In the first case, there are four five possible expressions to match: Times[2, x, y]
(first), then the part Times
(the Head
or part 0), and then parts 1 through 3, that is 2
, x
, y
in any order. Because Times
is Flat
, the pattern Times[2, x]
can be applied to the first one, Times[2, x, y]
, matching the subexpression as if the whole were (2 x) y
. From the tutorial:
However, if you have a flat function, it is sometimes possible to apply transformation rules even though not all the arguments are covered.
In[13]:= a + b + c /. a + c -> p
Out[13]= b + p
But since Times[2, x, y]
was the whole expression, there is nothing left to apply the rules to. Note this explains why y
is not replaced in this case, too:
2 x y /. {2 x -> a, y -> b}
(* a y *)
In the second example above, again a rule may be applied to Times[2, x, y]
, this time 2 x y -> b
. Again ReplaceAll
stops after this for the same reason.
Finally, both rules are applied below in
2 x y /. {x -> a, y -> b}
(* 2 a b *)
because nothing can be applied to Times[2, x, y]
, but x -> a
and y -> b
can each be applied to one of the parts of the expression.
Update - I lost my Head
(see above, too)
Examples related to the head of the expression, Times
:
2 x y /. {Times -> List, 2 x -> a} (* the whole transformed, part Times not replaced *)
(* a y *)
2 x y /. {Times -> List, x -> a} (* Head and subpart transformed *)
(* {2, a, y} *)
FullForm[]
of the expression you're trying to change will prove illuminating. $\endgroup$ – J. M.'s ennui♦ Jul 14 '15 at 21:26I
. I think that should also clarify what @Guesswho was hinting at. $\endgroup$ – MarcoB Jul 14 '15 at 22:43