3
$\begingroup$

I know this question has been asked multiple times before but unfortunately it seems like I'm too dumb to understand what is really going on and how to solve this.

Anyway, I want to resubstitute certain parts of an equation but also on all levels of that equation. My minified problem looks like this:

G = 4/3 x a - 4/3 y b - z^2;
rules = {4/3 x -> r1, 4/3 y -> r2, z^2 -> r3};

t1 = ReplaceAll[G, rules]
t2 = ReplaceRepeated[G, rules]

t3 = Replace[G, rules, All]
t4 = Replace[G, rules, {0, Infinity}]

For completion, the FullForm of G looks like this:

Plus[Times[Rational[4, 3], a, x], Times[Rational[-4, 3], b, y], Times[-1, Power[z, 2]]]

If I understand it right, then ReplaceAll will replace my substitutions but only on level 0. ReplaceRepeated has the same problem and Replace, even when specifying levelspec won't work either. This is the output of the above test:

(* t1 *) a r1 - r3 - (4 b y)/3
(* t2 *) a r1 - r3 - (4 b y)/3
(* t3 *) -r3 + (4 a x)/3 - (4 b y)/3
(* t4 *) -r3 + (4 a x)/3 - (4 b y)/3

I can see that in the second term (4/3 y) can't be replaced because Mathematica treats it as Times[Rational[-4, 3], b, y] and the - does not correspond to the replacement rule. I have no clue why both cases of Replace don't work at all...

Is there a way to apply these replacement rules to any level of the equation? Can someone explain me what is going on here?

$\endgroup$
1
  • 1
    $\begingroup$ "If I understood right then ReplaceAll will replace my substitutions but only on level 0. " - a good place to verify this is documentation for ReplaceAll: "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." $\endgroup$
    – Kuba
    Commented Mar 13, 2018 at 11:07

1 Answer 1

2
$\begingroup$

Your problem isn't really about specifying the levels at which the various replacement function do their work. It really about formulating the right replacement rules. ReplaceAll is fine your task. One approach is to apply more abstract replacement rules.

exp = 4/3 x a - 4/3 y b - z^2;
rules = {_Rational x -> r1, _Rational y -> r2, z^2 -> r3};
exp /. rules

a r1 + b r2 - r3

If, for some reason, you need to be specific about the rational coefficient being 4/3, then you can use

coef = (4/3 | -4/3);
rules = {coef x -> r1, coef y -> r2, z^2 -> r3};

This extra fussiness comes about because the Wolfram Language doesn't use a subtraction function internally and changes all subtraction into addition.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.