2
$\begingroup$

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

$\endgroup$
7
  • $\begingroup$ 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? $\endgroup$
    – Mr.Wizard
    Commented Oct 13, 2014 at 6:31
  • $\begingroup$ it is long answer and need some time to digest. any way thanks for the comment or I should say the answer :) $\endgroup$ Commented Oct 13, 2014 at 6:40
  • $\begingroup$ 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. $\endgroup$
    – Mr.Wizard
    Commented Oct 13, 2014 at 6:44
  • $\begingroup$ Good question by the way, so +1 despite the (possible) duplicate. $\endgroup$
    – Mr.Wizard
    Commented Oct 13, 2014 at 6:47
  • 1
    $\begingroup$ 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 :) $\endgroup$ Commented Oct 13, 2014 at 6:48

0

Browse other questions tagged or ask your own question.