I am a little confused about:

In what order is a Rule tried to apply to an expression? In a depth-first order or otherwise?

For example,

f[x + f[y]] /. f[u_] -> g[u]


g[x + f[y]]

which looks like the rule was first tried at the outermost level. And "the result was returned as soon as the rule had been applied".

However, if the actual pattern part [u_] was dropped,

f[x + f[y]] /. f -> g

the output changed to

g[x + g[y]]

which looks like the new rule was first tried at the innermost level. And tried repetitively to the "shallower" levels.

If we follow the behavior observed in the first example, the output should have been

g[x + f[y]]

So why are two rules tried in different orders?

  • $\begingroup$ ReplaceAll/Details. In second example you are replacing heads only so what's inside is not skipped like in first one. $\endgroup$
    – Kuba
    Oct 25, 2014 at 4:10
  • $\begingroup$ @Kuba Pardon me, I am so silly...I can't stop tending to treat head of an expression and [...] part as a whole...And constantly forget they are actually treated independently, unless they are covered in a single pattern. $\endgroup$
    – Naitree
    Oct 25, 2014 at 4:20
  • 2
    $\begingroup$ Don't be sorry ;) we all are learning new things each day :) $\endgroup$
    – Kuba
    Oct 25, 2014 at 4:32
  • 2
    $\begingroup$ It depends on whether you use ReplaceAll or Replace. Please see: (9233), (38668), (56010), (56016), (57361), (20181). $\endgroup$
    – Mr.Wizard
    Oct 25, 2014 at 5:14
  • $\begingroup$ Thanks a lot for references, Mr. Wizard. :-) $\endgroup$
    – Naitree
    Oct 25, 2014 at 5:17


Browse other questions tagged or ask your own question.