具有无序子表达式的模式 [英] Patterns with Orderless subexpressions

查看:26
本文介绍了具有无序子表达式的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要处理像 f[{a,b}]=... 这样的模式,其中 ab 应该是无序

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

到目前为止,我已经通过在每次定义或评估 f 时对子表达式使用默认的 Sort[] 来实现这一点.

So far I've implemented this by using default Sort[] on subexpressions every time f is defined or evaluated.

我的问题是

  1. 这是否与 Orderless 一样强大?
  2. 有更好的方法吗?

PS:一个示例应用程序是树分解,您可以递归地构建数量,例如 subtree[bag1->bag2],其中 bag1 和 bag2 是无序顶点集

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

答案更新

Michael Pilat 的回答展示了如何定义规则来自动对 f 的子表达式进行排序.另一种解决方案是定义一个像 Bag 这样具有 Orderless 属性的自定义头部,并将该头部用于任何无序子列表

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

或者,您可以使用具有 Orderless 属性的自定义头部符号替换内部 List 头部,如果格式真的很重要,您可以使用各种格式技术最近在这里讨论过 =)

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

这篇关于具有无序子表达式的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆