       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:= On[]
During evaluation of In:= On::trace: On[] --> Null. >>

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

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

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

In:= 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)

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