TransWikia.com

How can I emulate Orderless attribute?

Mathematica Asked on August 22, 2021

Suppose I want an expression to automatically sort its arguments. This can be done via

SetAttributes[f, Orderless]
f[3, 2, 1]
(*output is f[1, 2, 3]*)

Just as an exercise, I want to emulate this behavior myself with

f[x__] := f[Sequence @@ Sort[{x}]]

which doesn’t work due to infinite iteration.

I would be enlightened if anyone can show me an example how to implement this.

One Answer

A couple of ways:

f[x__] /; ! OrderedQ[{x}] := f @@ Sort[{x}]

call : f[x__] := Block[{f}, Sort[call] /; ! OrderedQ[call]]

The first way seems better, or at least faster.

Correct answer by Michael E2 on August 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP