Modeless subexpression patterns

I need to deal with patterns like f[{a,b}]=... where a and b must be empty

So far, I have implemented this using the default Sort[] in subexpressions every time f is defined or evaluated.

My questions

  • Is it as reliable as Orderless ?
  • Is there a better way?

PS: an example application is a tree decomposition in which you recursively increase quantities, such as the subtree [bag1-> bag2], where bag1 and bag2 are ordered vertex sets

reply to update

Michael Pilate's answer shows how to define a rule to automatically sort f subexpressions. An alternative solution is to define a custom head of type Bag with the attribute Unlimited and use this head for any ordered subscriptions

+4
wolfram-mathematica
source share
1 answer

After I answered this question , I consulted with several colleagues who agreed that the best and typical way to solve this problem is:

 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}}] 

Alternatively, you can replace the internal List heads with a custom head symbol that has the Orderless attribute, and if formatting really matters, you can use various formatting methods that were recently discussed here =)

+4
source share

All Articles