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.
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
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP