MathGroup Archive 2003

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

Search the Archive

RE: Bug in ReplaceAll and ReplaceRepeated?

  • To: mathgroup at
  • Subject: [mg44029] RE: [mg44018] Bug in ReplaceAll and ReplaceRepeated?
  • From: "David Park" <djmp at>
  • Date: Sat, 18 Oct 2003 03:12:22 -0400 (EDT)
  • Sender: owner-wri-mathgroup at


I think it is a feature. The notes say:

"ReplaceAll looks at each part of expr, tries all the rules on it, and then
goes on to the next part of expr. The first rule that applies to a
particular part is used; no further rules are tried on that part, or on any
of its subparts."

But that seems vague to me because it does't tell what order is used to look
at subparts of an expression. I think Mathematica looks at higher levels

Sqrt[(X + Y + Z)^2] //. {Z -> 2, (a_ + b_)^c_ :> Expand[(a + b)^c]}

On the first pass the highest level subexpression that matches any rule is
the inner square power. The Sqrt does not match because there is only one
term. So the inner power is expanded.

On the second pass the whole expression matches because you have a Power
expression with at least two terms. (a_ + b_) will match more than two terms
because Plus is Flat. But Expand does nothing with a power of 1/2 so the
result is unchanged and ReplaceRepeated stops.

Once a rule on the list is applied to an expression or subexpression, no
other rules on the list are applied to the same subexpression. So the Z rule
never gets a chance to be applied.

The moral is that one has to be careful in combining a rule that will always
match with rules that will only sometimes match in the same list. A rule
that always matches some expression will block out a rule that only matches
subparts of the same kind of expression.

You could make the power rule more specific...

Sqrt[(X + Y + Z)^2] //. {Z -> 2, (a_ + b_)^2 :> Expand[(a + b)^2]}

Or you could do sequential ReplaceAlls

Sqrt[(X + Y + Z)^2] /. Z -> 2 /. (a_ + b_)^c_ :> Expand[(a + b)^c]

David Park
djmp at

From: Artûras Acus [mailto:acus at]
To: mathgroup at


Sqrt[(X + Y + Z)^2] //. {Z -> 2, (a_ + b_)^c_ :> Expand[(a + b)^c]}

don't replace Z with 2. If I remove c in right hand side of second rule,
works as expected.

is the following behaviour bug or the feature?
In applies both to 4.1, and 5.0.

  • Prev by Date: Re: serious NDSolve bug?
  • Next by Date: Re: What Happens to Garbage in Mathematica?
  • Previous by thread: RE: Bug in ReplaceAll and ReplaceRepeated?
  • Next by thread: Running The Combinatorica GraphEditor