具有给定顺序的无序数据类型集
我试图将此数据类型放入 Haskell Set 中,但我不想给它一个 Ord 的通用实例。所以我想在 y 坐标上给集合一个排序,但没有实例 Ord Vector。这可能吗?
data Vector = V
{ x :: Double
, y :: Double
} deriving (Eq)
I'm trying to put this data type in a Haskell Set, but I don't want to give it a general instance of Ord. So I want to give the set an ordering on y-coördinate but without instance Ord Vector. Is this possible?
data Vector = V
{ x :: Double
, y :: Double
} deriving (Eq)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Set
要求您使用元素类型的默认Ord
实例。如果您想使用不同的
Ord
实例,标准方法是使用自定义newtype
包装器,然后编写一个Ord
实例 。但由于这种比较方式与二进制元组的比较方式等效,因此 KennyTM 的解决方案是最简单的
Set
requires you to use the defaultOrd
instance of the element type.If you want to use a different
Ord
instance, the standard way to do that is to use a customnewtype
wrapper and then write anOrd
instance for that:But since this way of comparing is equivalent to the way binary tuples are compared, KennyTM's solution is the simplest here.
您可以将向量转换为元组:
由于元组派生 Ord(使用字典顺序比较),因此可以将它们插入到 Set 中。 (定义 2 个其他函数用于 x 大排序。)
You can convert the vector into a tuple:
Since tuples derive Ord (using lexicographic comparison), they can be inserted to the Set. (Define 2 other functions for x-major ordering.)
我制作了
Set
数据类型的一个版本,它没有Ord
上下文,但需要一个a ->; 类型的函数。一个->在构造
。这对你的情况有用吗?Set
的任何地方都会传递 Ordering(我不确定版权状态,它很大程度上未经测试,文档也没有修改,所以我不只是把它放在这里......)
I've made a version of the
Set
datatype which does not have theOrd
context, but instead needs a function of typea -> a -> Ordering
passed in wherever aSet
is constructed. Could that be useful in your case?(I'm not sure about the copyright status, it's largely untested and the documentation is not modified, so I'm not just putting it up here...)