Re: ReplaceAll behavour

• To: mathgroup at smc.vnet.net
• Subject: [mg82134] Re: ReplaceAll behavour
• From: Szabolcs Horvát <szhorvat at gmail.com>
• Date: Sat, 13 Oct 2007 03:46:15 -0400 (EDT)
• References: <fen6q6\$54t\$1@smc.vnet.net>

```magma wrote:
> I do not understand what Mathematica 6 is doing here:
>
> a=5
> a/.a->3
>
> gives 3
>
> But...
>
> a+2/. a->3
>
> gives 7
>
> Why is that?
>
> Thank you for your help
>

Hi,

Use Trance[a /. a->3] or On[] and Off[] to find out how Mathematica
evaluates an expression.  The following output should explain what happens:

In[1]:= On[]
During evaluation of In[1]:= On::trace: On[] --> Null. >>

In[2]:= a=5
During evaluation of In[2]:= Set::trace: a=5 --> 5. >>

Out[2]= 5
In[3]:= a/.a->3
During evaluation of In[3]:= a::trace: a --> 5. >>
During evaluation of In[3]:= a::trace: a --> 5. >>
During evaluation of In[3]:= Rule::trace: a->3 --> 5->3. >>
During evaluation of In[3]:= Rule::trace: 5->3 --> 5->3. >>
During evaluation of In[3]:= ReplaceAll::trace: a/.a->3 --> 5/.5->3. >>
During evaluation of In[3]:= ReplaceAll::trace: 5/.5->3 --> 3. >>
Out[3]= 3

In[4]:= (a+2)/.a->3
During evaluation of In[4]:= a::trace: a --> 5. >>
During evaluation of In[4]:= Plus::trace: a+2 --> 5+2. >>
During evaluation of In[4]:= Plus::trace: 5+2 --> 7. >>
During evaluation of In[4]:= a::trace: a --> 5. >>
During evaluation of In[4]:= Rule::trace: a->3 --> 5->3. >>
During evaluation of In[4]:= Rule::trace: 5->3 --> 5->3. >>
During evaluation of In[4]:= ReplaceAll::trace: a+2/.a->3 --> 7/.5->3. >>
During evaluation of In[4]:= ReplaceAll::trace: 7/.5->3 --> 7. >>
Out[4]= 7

In[5]:= Off[]

Szabolcs

P.S.

This is why it is a bad idea to do things like

sqrt[a_?NumericQ] := x /. FindRoot[x^2 == a, {x, 1}]

(Even though this function works correctly almost all the time -- one
must come up with a really tricky definition for 'x' to make it fail,
like x = Sequence[1])

So use Module[] to localise 'x':

sqrt[a_?NumericQ] := Module[{x}, x /. FindRoot[x^2 == a, {x, 1}]]

```

• Prev by Date: Re: Re: What is the purpose of the Defer Command?
• Next by Date: Re: Non-numeric arguments to Compile-d functions
• Previous by thread: Re: ReplaceAll behavour
• Next by thread: import function