1

1. Default behavior of Sort

Note: this peculiarity is described in a comment to a related question at StackOverflow but I think it's worth restating here at mma.sx.

It is estabilished in documentation that Sort uses OrderedQ by default:

Sort[list, p] applies the function p to pairs of elements in list to determine whether they are in order. The default function p is OrderedQ[{#1, #2}]&.

However, modification of OrderedQ doesn't really change the default behavior of Sort:

Unprotect@OrderedQ;
OrderedQ[{special2, special1}, ___] := True; 
OrderedQ[{special1, special2}, ___] := False;
Protect@OrderedQ;

Sort@{special2, special1}
{special1, special2}

unless you explicitly mention that it should be default:

Sort[{special2, special1}, OrderedQ@{#1, #2}&]
{special2, special1}


2. Is specifying global custom sorting rules possible?

Suppose I have InitialObject@"X" and FinalObject@"Y", and I want to always put InitialObject before FinalObject. Lots of Mathematica's internal functions would be affected then, I guess, but I still think it's fairly legit to add special ordering rules for special expressions, especially if they are properly kept in packages. Is it possible to specify ordering rules for expressions, say, of the form InitialObject@___ and FinalObject@___, similar to

OrderedQ[{_InitialObject, _FinalObject}, ___] := True
OrderedQ[{_FinalObject, _InitialObject}, ___] := False

so that they are automatically applied inside Plus, Times, when Union is called, etc.? So far I tried what is described in 1. Tried redefining Order as well, to no effect. (Version 8)

My research of StackExchange archives suggests it's not possible but I still hold some hope. I think I'd use whatever dirty hack offered.

akater
  • 1,540
  • 11
  • 16
  • related: https://mathematica.stackexchange.com/questions/31261/is-there-a-precedence-table-for-the-canonical-sort-ordering – akater Feb 11 '15 at 09:12
  • If this is for display purposes using Block[{$Post = myOrder},...] in your package might help. – C. E. Feb 11 '15 at 14:27
  • “I think I'd use whatever dirty hack offered.” — Or maybe not. It would probably affect pattern matching in definitions, e.g. of the form f@g@x___ where g is Orderless. – akater Feb 14 '15 at 17:34

0 Answers0