# What is the function of OrderedQ in these expressions?

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.

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]*)

• 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. – Szabolcs Aug 1 '16 at 16:04
• @Szabolcs I'll poke at it. – rcollyer Aug 1 '16 at 18:22