Patterns with Orderless subexpressions
I need to deal with patterns like f[{a,b}]=... where a and b are supposed to be orderless
So far I've implemented this by using default Sort[] on subexpressions every time f is defined or evaluated.
My questions are
- Is this as robust as
Orderless? - Is there a better way?
PS: An example application is tree decomposition where you recursively build up quantities like subtree[bag1->bag2] where bag1 and ba开发者_开发问答g2 are orderless sets of vertices
answer update
Michael Pilat's answer shows how to define a rule to automatically sort f's subexpressions. Alternative solution is to define a custom head like Bag with Orderless attribute and use that head for any orderless sublists
After I answered this question I consulted with a few colleagues who agreed that the following is indeed the best / typical way to handle this problem:
f[{a_, b_}] :=
f[{Sort[a], Sort[b]}] /; Not[OrderedQ[a]] || Not[OrderedQ[b]]
In[99]:= f[{{1, 2, 3}, {5, 4, 3}}]
Out[99]= f[{{1, 2, 3}, {3, 4, 5}}]
Alternately, you could replace the inner List heads with a custom head symbol that has the Orderless attribute, and if formatting really matters you could use the various formatting techniques that have recently been discussed here =)
加载中,请稍侯......
精彩评论