Patterns with Orderless subexpressions

心已入冬 提交于 2019-12-13 13:24:45

问题


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

  1. Is this as robust as Orderless?
  2. 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 bag2 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


回答1:


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 =)



来源:https://stackoverflow.com/questions/4189895/patterns-with-orderless-subexpressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!