Why does the following replacement rule not work?

term = x^2/y^2 + x^3/y^3

term /. u_^p_/v_^p_ -> z^p

I expected it to return z^2 + z^3.

=================

2

take a look at FullForm[term]

– george2079

Jun 2 ’15 at 19:50

=================

2 Answers

2

=================

term /. Times[Power[x_, n_], Power[y_, m_]] /; m == -n :> z^n

or

term /. (x_^n_) (y_^m_) /; m == -n :> z^n

z^2 + z^3

Check full form of the summand in your term, x^2 / y^2:

x^2 / y^2 // FullForm

Times[Power[x,2], Power[y,-2]]

Compare this to FullForm or your pattern:

u_^p_ / v_^p_ // FullForm

Times[

Power[Pattern[u, Blank[]], Pattern[p, Blank[]]],

Power[Pattern[v, Blank[]], Times[-1, Pattern[p, Blank[]]]]]

You may notice there is a difference between internal representations of -2 and -p: the first one is Integer expression (that is, expression with Head Integer), the second one is Times expression, since it’s a product of -1 and p (in your case it’s Pattern[p, Blank[]], rather than simply p). This is why there is no match.

In general, use of complicated expressions in patterns requires some care. This will not work:

(1/3) /. (1/a_) :> a

1 / 3

Much like in your example, 1/3 is â€œa straightforward numberâ€, and as such is treated not like a more general expression (1/a_):

1/3 // FullForm

Rational[1, 3]

The pattern 1/a_ is not a rational number, hence it’s not represented as Rational expression, and again, there’s no match.