为数据类型定义自己的Ord [英] Defining own Ord for a data type
问题描述
我正在尝试建立一些数据结构来解决图形难题。我正在尝试定义边缘的比较标准,但不确定如何。到目前为止:
I am attempting to make some data structures to solve a graph puzzle. I am trying to define an edge's comparison criteria, but I am not sure how. So far:
data Edge = Edge (Set String) Bool
如果它们具有相同的字符串集,但不具有相等性,我如何通知编译器我希望将边声明为相等,则与布尔值有任何关系值?
How can I 'inform' the compiler that I want edges to be declared equal if they have identical sets of strings, and not have equality have anything to do with the boolean value?
推荐答案
虽然我不确定为什么要忽略布尔值(我很好奇),但是因此您必须定义自己的 Eq
实例;默认设置无效,因为它会比较每个字段。幸运的是,这很容易:
Although I'm not sure why you want to ignore the boolean value (I'm curious), to do so you'll have to define your own Eq
instance; the default one won't work, as it compares every field. Luckily, this is easy:
instance Eq Edge where
(Edge s1 _) == (Edge s2 _) = s1 == s2
如果您想订购边缘,并且希望订购仅比较集合,您的实现也非常相似:
If you want to be able to order edges, and you want the ordering to compare just the sets too, your implementation is very similar:
instance Ord Edge where
(Edge s1 _) `compare` (Edge s2 _) = s1 `compare` s2
每个类型类都定义了一组需要实施的方法; Eq
需要 ==
或 / =
和 Ord
需要< =
或 compare
。 (要了解哪些功能是必需的,哪些是可选的,可以检查文档。)
Each type class defines a certain set of methods which need to be implemented; Eq
requires ==
or /=
, and Ord
requires <=
or compare
. (To find out which functions are required and which are optional, you can check the docs.)
这篇关于为数据类型定义自己的Ord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!