Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I need to do a little more research, but here's two ways; The catch is, you don't actually use the <code>Orderless</code> attribute. Simon should get half-credit for the technique of using pattern-matching with a condition from <a href="https://stackoverflow.com/questions/3947071/controlling-order-of-variables-in-an-expression/3948995#3948995">his answer to question 1</a> you referenced. </p> <p>Messing with <code>Order</code>, <code>OrderedQ</code> and <code>Sort</code> won't get you anywhere, because <code>Orderless</code> functions sort with <em>equivalence</em> to those methods, but does not actually sort <em>with</em> them.</p> <p>The first method, from Simon's answer, is to use a <a href="http://reference.wolfram.com/mathematica/ref/Condition.html" rel="nofollow noreferrer"><code>Condition</code></a>:</p> <pre><code>In[1]:= ClearAll[f, g] In[2]:= f[stuff__] /; ! OrderedQ[{stuff}, Greater] := f[Sequence@@Sort[{stuff}, Greater]] In[3]:= f[1, 2, 3] Out[3]= f[3, 2, 1] In[4]:= f[3, 2, 1] Out[4]= f[3, 2, 1] </code></pre> <p>That definition of f[stuff__] is evaluated if the order of the arguments is not the order desired, and then transformed into that order. </p> <p>Another technique is to get a little more low-level and use <a href="http://reference.wolfram.com/mathematica/ref/%24Pre.html" rel="nofollow noreferrer"><code>$Pre</code></a> or <a href="http://reference.wolfram.com/mathematica/ref/%24PreRead.html" rel="nofollow noreferrer"><code>$PreRead</code></a>:</p> <pre><code>In[5]:= $Pre = Function[{expr}, expr /. g[stuff__] :&gt; g[Sequence @@ Sort[{stuff}, Greater]]]; In[6]:= g[1, 2, 3] Out[6]= g[3, 2, 1] In[7]:= g[3, 2, 1] Out[7]= g[3, 2, 1] </code></pre> <p>There are some issues with both of these approaches as they stand, for example, that particular <code>$Pre</code> function doesn't play well with e.g. <code>HoldForm[g[1,2,3]]</code>. </p> <p>So, that's something to play with for now. I hope to update after I do a little more research into this.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload