Haskell 为导入的数据类型派生其他实例

标签 haskell import types typeclass

我对 Haskell 比较陌生。我写了一个纸牌游戏 uno 的克隆,我想要一张漂亮的彩色纸牌输出。我愿意

import System.Console.ANSI

这提供了
data Color = Black
           | Red
           | Green
           | Yellow
           | Blue
           | Magenta
           | Cyan
           | White
           deriving (Bounded, Enum, Show)

现在我也想添加派生(Ord,Eq),我可以在导入包的源文件中编写它,但应该有一种更简单的方法来做到这一点。
我不知道要谷歌搜索或在书中寻找什么关键字。

最佳答案

无需编辑库。在您的源文件中,声明:

instance Eq Color where
  x == y  =  fromEnum x == fromEnum y

instance Ord Color where
  compare x y  =  compare (fromEnum x) (fromEnum y)

说明:fromEnumEnum 上的一个函数返回 int ( Black -> 0Red -> 1 等)。整数显然是等式可比和有序的。

编辑 :@rampion 的版本,在评论中,显然更漂亮:
instance Eq Color where
  (==)  =  (==) `on` fromEnum

instance Ord Color where
  compare  =  compare `on` fromEnum

关于Haskell 为导入的数据类型派生其他实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5841129/

相关文章:

scala - 这是Scala中一种更高种类的类型吗?

sql boolean 数据类型替代

c# - typeof(Foo) 有效,但 Type.GetType ("Foo") 为 null

Haskell 函数依赖 a b -> c 取决于 c?

haskell - 如何测试 float 是否是haskell中的整数?

python - 导入 F2Py 模块时如何出现 "catch"段错误?

python - 如何从 Django 迁移中调用基于实例的函数并访问实例变量

github - 如何从 Google Colab 的 Github 存储库导入自定义模块?

haskell - 尝试一些 Yesod 示例时出现编译错误

haskell - 无法理解 Monad >> 应用程序的结果