我对 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)
说明:
fromEnum
是 Enum
上的一个函数返回 int
( Black -> 0
、 Red -> 1
等)。整数显然是等式可比和有序的。编辑 :@rampion 的版本,在评论中,显然更漂亮:
instance Eq Color where
(==) = (==) `on` fromEnum
instance Ord Color where
compare = compare `on` fromEnum
关于Haskell 为导入的数据类型派生其他实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5841129/