为数据类型定义自己的Ord(Haskell) [英] Defining your own Ord for a data type (Haskell)

查看:756
本文介绍了为数据类型定义自己的Ord(Haskell)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一些数据结构来解决图形难题。我正在试图界定一个边缘的比较标准,但我不知道如何。到目前为止:

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 do I tell let the compiler know 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 instance;默认值将不起作用,因为它比较每个字段。幸运的是,这很简单:

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 需要 <= 比较。 (要了解哪些功能是必需的,哪些是可选的,可以查看文档。)

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(Haskell)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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