Could someone please let me why the output of the two expressions change with OrderedQ in place. The first expression is as follows:

-o[a - b]/. o[n_? Negative x_ + y_] :> -o[- n x - y]

The output of the above expression is: o[-a + b]

The second expression being:

 -o[a - b]/. o[n_? Negative x_ + y_] :> -o[- n x - y]/;OrderedQ[{x,y}]

The output of the second expression is: -o[a - b]

The second expression yields the correct output (Computer Science with Mathematica, Roman Maeder). What is confusing me is why OrderedQ corrects for the discrepancy.


1 Answer 1


This is a case where deconstructing the right hand side of the replacement rule is very helpful. Let us look at the first example,

-o[a - b]/. o[n_? Negative x_ + y_] :> -o[- n x - y]

and change a few things

o[a - b]/. o[n_? Negative x_ + y_] :> {n, x, y}

which returns

{-1, b, a}

Note, I dropped the $-1$ in front since it would just negate everything in the list. Doing something similar with the second pattern

o[a - b] /. o[n_?Negative x_ + y_] :> {n, x, y, OrderedQ[{x, y}]}

we get

{-1, b, a, False}

This tells us that OrderedQ is passed {b, a}, which is not in sorted order, so it returns False. In your second pattern, this has the effect that the minus sign needs to be on a, not b, for the pattern to activate, e.g.

-o[-a + b] /. o[n_?Negative x_ + y_] :> -o[-n x - y] /; OrderedQ[{x, y}]
(*o[a - b]*)
  • $\begingroup$ This looks like a graphics bug. I tried to reduce the example a but. Just wanted to point it out in case you don't know about it yet. $\endgroup$
    – Szabolcs
    Aug 1, 2016 at 16:04
  • $\begingroup$ @Szabolcs I'll poke at it. $\endgroup$
    – rcollyer
    Aug 1, 2016 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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