&gt; <i>I want to rewrite &quot;sum(reverse(x))&quot; without explicitly saying so.</i><p>You can endow functions with attributes (standard functions in the language library, and possibly user-defined ones). The reverse function can carry the attribute that it only changes the order of the elements of its argument. This is encoded as some boolean predicate:  (order-identity-p x) is true if x is reverse. And if x is other things, like the identity function, the sort function and whatnot.<p>Then our optimzer looks for the pattern&#x2F;rewrite  (sum (f? arg?)) -&gt; (sum arg?), where there is a semantic constraint: the pattern matches subject to the predicate (order-identity-p f?).  This is effectively part of the match; if the predicate fails, there is no match.<p>Now the sum function could also be &quot;patterned out&quot;. There could be a predicate which asserts that certain arguments of a function are sequences whose order doesn&#x27;t matter to the outcome.  This predicate could be list valued. If an argument has no such arguments, it returns nil&#x2F;false, otherwise a list of the argument positions or whatever.<p>So then we&#x27;re looking for the pattern (f? (g? arg?)) -&gt; (f? arg) which is very general, and can be met in lots of ways.  For instance, suppose f? and g? are the same function, and f? is idempotent.    One of the rules that applies is that g? satisfies (order-identity-p g?), and (order-irrelevant-args f?) returns (1), where we note that (g? ...) is argument 1 of f?.  For any argument  argument expression which is an orer-identity-p function call, if that argument&#x27;s position is in the list returned by order-irrelevant-args on the main constituent function, we can remove that order-altering function from the argument.<p>We code all that up into the tree walking engine, and then just suitably declare attributes on functions.