(in the first i should say may be the title is not very accurate)

how to understand case like the following:

Replace[f[1],f[x_]->x+1] (*ans is 2*)
Replace[f[1],f[x_]->x+1] (*ans is 11*)

this kind behavior of Mathematica make me feel unsafe when i use variable, that means if i happen to define x in another place, then the Replace[] I wrote here will be wrong, so I have to be very careful with the renaming of variable names.


  1. how to understand case in the above? why grammar of Mathematica can't be design so that the x_ in Replace is local(ie won't be influenced by the outside x)?
  2. In addition to the approach -- pay attention not use same variable name in Replace[], is there another way which can save my attention?
  • 7
    $\begingroup$ Try RuleDelayed :> instead of ->. $\endgroup$
    – Syed
    Commented Dec 31, 2022 at 12:11
  • 3
    $\begingroup$ "->" will evaluate the right hand side at once and take whatever values are available for the variables. However, ":>" waits until it is applied and the variables have been matched to corresponding values. The mechanism used with ":>" is similar to "Block", loock it up in the manual. $\endgroup$ Commented Dec 31, 2022 at 12:47
  • 2
    $\begingroup$ To add to the comments above, I find it convenient and safer to use RuleDelayed (:>) whenever the left-hand side portion of the replacement rule contains a named pattern. This avoids exactly the kinds of problems you see here. Although there may well be cases where this would not be appropriate, for general use I find that there are practically no downsides to defaulting to :> when dealing with named patterns. $\endgroup$
    – MarcoB
    Commented Dec 31, 2022 at 21:13


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.