MathGroup Archive 2010

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

Search the Archive

Re: precedence for ReplaceAll?

  • To: mathgroup at
  • Subject: [mg110543] Re: precedence for ReplaceAll?
  • From: Albert Retey <awnl at>
  • Date: Fri, 25 Jun 2010 07:25:27 -0400 (EDT)
  • References: <hvv4ti$fc$>

Am 24.06.2010 10:27, schrieb Matthias Fripp:
> 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?

No, what actually happens is that a and b are evaluated to A*c and B*c
respectively, even before the ReplaceAll sees them. Then the ReplaceAll

A*c+B*c /. {A*c -> x, B*c -> y}
A*B*c^2 /. {A*c -> x, B*c -> y}

where it will find matches in the first case but not in the second and
so does nothing. There are two things you need to understand: first is
the evaluation order, second is the fact that replacement rules work on
structure, not on mathematical relations. Both are topics that you will
a lot of information in the documentation and in the archive of this
group. I would recommend to search for "evaluation order" and "pattern
matching" in the documentation and read, well as much as you want to



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