# How exactly does ReplaceAll work? [duplicate]

I am not sure if this question has been asked before but anyway, Consider these two examples:

h[x + h[y]] /. h[u_] :> g[u]

(*g[x + h[y]]*)

h[x + h[y]] /. h :> g

(*g[x + g[y]]*)


In the first one, the rules apply starting from outer level and once it applies then it stops. however, in the second example the rules apply up to the lowest level.

any explanation why there is different in the way ReplaceAll work.

thanks

• I think this question is well addressed in my answer to: (56010) -- would you please review that and tell me if you feel it is not adequate? – Mr.Wizard Oct 13 '14 at 6:31
• it is long answer and need some time to digest. any way thanks for the comment or I should say the answer :) – Algohi Oct 13 '14 at 6:40
• Let me attempt to be succinct: ReplaceAll traverses the expression in the same way in both your examples. In the first example the entire expression is replaced in the first match and traversal stops. (No traversal takes place on the substituted parts.) In the second example h[y] is not part of the expression that is replaced after the first match therefore it is exposed to additional traversal. – Mr.Wizard Oct 13 '14 at 6:44
• Good question by the way, so +1 despite the (possible) duplicate. – Mr.Wizard Oct 13 '14 at 6:47
• Ahaaa, got it. so that is the secret. thanks. you know, this comment "in my opinion" is more straightforward and shorter and to the point compared to your answer in the link. thanks a lot :) – Algohi Oct 13 '14 at 6:48