2

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

Basheer Algohi
  • 19,917
  • 1
  • 31
  • 78
  • 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 06:31
  • it is long answer and need some time to digest. any way thanks for the comment or I should say the answer :) – Basheer Algohi Oct 13 '14 at 06: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 06:44
  • Good question by the way, so +1 despite the (possible) duplicate. – Mr.Wizard Oct 13 '14 at 06:47
  • 1
    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 :) – Basheer Algohi Oct 13 '14 at 06:48
  • if I would add something I would say that in the first example I am replacing and expression (which have subexpression). in the second example I am replacing and Atom which does not have a subexpression (the second h is not a subexpression of the first h). – Basheer Algohi Oct 13 '14 at 06:56
  • I do tend to ramble a bit; sorry. For what it's worth I think the answer (and the links) are worth reading, if you have the interest. Regarding your second comment "the second h is not a subexpression of the first h" is an even more succinct way of putting it; however I think referencing "Atom" is misguided as it really don't matter whether or not it is an atom but rather only if the expression is part of an earlier substitution. – Mr.Wizard Oct 13 '14 at 07:01

0 Answers0