TransWikia.com

How can I emulate Orderless attribute?

Mathematica Asked on October 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.

Answered by Michael E2 on October 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