MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: precedence for ReplaceAll?

[note: message sent to comp.soft-sys.math.mathematica as well]

On 2010.06.24. 10:27, Matthias Fripp wrote:
> I am having trouble using ReplaceAll to replace symbols that already
> have a delayed assignment.
> e.g., this input:
> In[287]:=
> a := A c
> b := B c
> a /. {a ->  x, b ->  y}
> b /. {a ->  x, b ->  y}
> a + b /. {a ->  x, b ->  y}
> a * b /. {a ->  x, b ->  y}
> gives this output:
> Out[289]= x
> Out[290]= y
> Out[291]= x + y
> Out[292]= A B c^2
> All of this works as expected except for the final term. I would have
> expected to get the result "x y". Is there any way to force
> Mathematica to produce that result?
> If on the other hand the original assignment is a := A + c and b := B
> + c, I get an unexpected output for the sum, but the expected output
> (x y) for the product. If I insert d instead of one of the c's, I get
> various other (unpredictable) kinds of result.
> My first guess is that Mathematica is doing a sort of "double
> ReplaceAll", where it first tries the pattern given in the delayed
> assignment, and any symbols matched by that are not tested against the
> explicit ReplaceAll. But that doesn't explain why the sum works and
> not the product. Am I thinking about this the wrong way?

I get the impression from your message that you believed that when 
evaluating a /. {a ->  x, b ->  y}, 'a' gets replaced by 'x'.  This is 
not the case.  First the 'a' on the lhs of /. is evaluated to A c, then 
the 'a' on the rhs is evaluated to A c (and 'b' is evaluated too, of 
course).  At this point the evaluator has the expression A c /. { A c -> 
x, B c -> y }, and replaces A c by x.  This is all easy to see by using 
the Trace function:

In[41]:= Trace[a/.a->x]
Out[41]= {{a,A c},{{a,A c},A c->x,A c->x},A c/.A c->x,x}

What happens with the last expression is this:

In[42]:= Trace[a b/.{a->x,b->y}]
Out[42]= {{{a,A c},{b,B c},(A c) (B c),A c B c,A B c c,A B c^2},{{{a,A 
c},A c->x,A c->x},{{b,B c},B c->y,B c->y},{A c->x,B c->y}},A B c^2/.{A 
c->x,B c->y},A B c^2}

I.e. the ReplaceAll expression evaluates to A B c^2 /. {A c->x,B c->y}, 
and no replacement can be done, as A c or B c do not appear *formally* 
in the expression A B c^2.

What you are looking for is achieved by

Unevaluated[a b] /. {HoldPattern[a] -> x, HoldPattern[b] -> y}

Hope this helps,

  • Prev by Date: Re: precedence for ReplaceAll?
  • Next by Date: Re: precedence for ReplaceAll?
  • Previous by thread: Re: precedence for ReplaceAll?
  • Next by thread: Re: precedence for ReplaceAll?