For example, the substitution (x + y) -> s fails here:

In[1]:= (-x - y) /. (x + y) -> s

Out[1]= -x - y

Of course, I could try applying the rule (-x - y) -> -s, but this strategy becomes unwieldy in more complicated cases. At the very least it would require duplicating a lot of rules. For example, if the expression to be transformed were something like

(x + y)^2 + 2 (-x - y)

...then I'd need to use something like

{(x + y) -> s, (-x - y) -> -s}

Is there a better way to transform the above expression to s^2 - 2 s?

  • 4
    $\begingroup$ Not sure if you find it better: expr /. x -> (s - y) $\endgroup$ – Kuba Jan 16 '14 at 20:03
  • 2
    $\begingroup$ Use FullForm[x + y] and FullForm[-x - y] to see how those two expressions are different (or TreeForm if you are feeling daring). ReplaceAll is a dumb function that is not going to transform your expression for you. It may not be friendly, but it is reliable. In general, as Kuba has suggested, it's better to replace atomic elements. $\endgroup$ – wxffles Jan 16 '14 at 21:54
  • $\begingroup$ It sounds like the transformation you are trying to do it more mathematica than formal. In these cases you can consider Eliminate or GroebnerBasis too, e.g. like here It depends on the situation if they work well. $\endgroup$ – Szabolcs Jan 16 '14 at 23:24

Here are two methods to create patterns that match; the first uses a default value, while the second uses an explicit Alternatives expression.

p1 = x (s_: - 1) + y (ss_: - 1);
p2 = (x | -x) + (y | -y);

expr = {x + y, x - y, -x + y, -y - x};

MatchQ[#, p1] & /@ expr
MatchQ[#, p2] & /@ expr
{True, True, True, True}

{True, True, True, True}

If you specify how you want to handle the sign in all cases I can recommend something for the replacement.

poly=(x + y)^2 + 2 (-x - y)//Simplify;
poly//.{(x + y)-> s}

(*(-2 + s) s*)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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