2
$\begingroup$

If I define an operator to be orderless

SetAttributes[CirclePlus,Orderless]

It puts the arguments into canonical sorting, i.e.

[In]:  CirclePlus[0, 2, 1]
[Out]: CirclePlus[0, 1, 2]

How can I make it, that it is sorted descendingly, i.e.

[Out]: CirclePlus[2, 1, 0]

I probably need to rewrite a specific output form, so it's fine if it doesn't work in StandardForm

$\endgroup$

1 Answer 1

1
$\begingroup$

Simple ways to change the order of the argument sequence:

CirclePlus[0, 2, 1]
CirclePlus[0, 2, 1] // Sort
CirclePlus[0, 2, 1][[{1, 3, 2}]]
CirclePlus[0, 2, 1] // RotateLeft
CirclePlus[0, 2, 1] // Sort // Reverse

For descending order (// Sort // Reverse):

Remove@"Global`oPlus" // Quiet
CirclePlus // ClearAll
oPlus[x__] := CirclePlus @@ Reverse@Sort@List@x

oPlus[0, 2, 8, 1]
oPlus[0, 2, 8, 1] // FullForm

function oPlus is defined and used here. This is exactly what desired: oPlus[0, 2, 8, 1] // FullForm gives CirclePlus[8,2,1,0] without setting any attributes.

What happens setting attribute Orderless, for example one consequence is:

(* With *)    CirclePlus[0, 2, 1] === CirclePlus[0, 1, 2]  (* is True  *)
(* Without *) CirclePlus[0, 2, 1] === CirclePlus[0, 1, 2]  (* is False *)

For changing the order of the argument sequence in the output (this is a formating issue), there is no need to set or clear the attribute Orderless, (this is a change of functionalty of CirclePlus). The output format may be changed by Format[], e.g.

ClearAll@CirclePlus;
Format[CirclePlus[z__], StandardForm] := 
 Row[#, "\[ThinSpace]"] &@Riffle[Reverse@Sort@{z}, "\[CirclePlus]"]
CirclePlus[0, 2, 1]
CirclePlus[0, 2, 1] // FullForm

CirclePlus[0, 2, 1] // FullForm shows the argument sequence stays unchanged only formatting is different. Note: ClearAll is needed to get rid off the Format definition, this can't be done with Remove@"Global`*"

$\endgroup$
3
  • $\begingroup$ I get the error "Format::nosym: z__ does not contain a symbol to attach a rule to." $\endgroup$ Aug 15, 2021 at 23:26
  • $\begingroup$ what os and version do you have? in mma 12.1 on win64 it works $\endgroup$
    – hieron
    Aug 15, 2021 at 23:31
  • $\begingroup$ I have an extra definition that causes it: CirclePlus[a_]:=a However, adding a HoldPattern around the first argument of Format is a fix. Thank you! $\endgroup$ Aug 15, 2021 at 23:34

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.