# Understanding the order of applying Rule to expression [closed]

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]


outputs

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?

• ReplaceAll/Details. In second example you are replacing heads only so what's inside is not skipped like in first one. – Kuba Oct 25 '14 at 4:10
• @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. – Naitree Oct 25 '14 at 4:20
• Don't be sorry ;) we all are learning new things each day :) – Kuba Oct 25 '14 at 4:32
• It depends on whether you use ReplaceAll or Replace. Please see: (9233), (38668), (56010), (56016), (57361), (20181). – Mr.Wizard Oct 25 '14 at 5:14
• Thanks a lot for references, Mr. Wizard. :-) – Naitree Oct 25 '14 at 5:17