eps*_*lbe 5 import haskell types typeclass
我对Haskell比较陌生.我写了一个卡片游戏uno的克隆,我想要一张漂亮的卡片输出.我做
import System.Console.ANSI
Run Code Online (Sandbox Code Playgroud)
提供
data Color = Black
| Red
| Green
| Yellow
| Blue
| Magenta
| Cyan
| White
deriving (Bounded, Enum, Show)
Run Code Online (Sandbox Code Playgroud)
现在我想添加deriving(Ord,Eq),我可以在导入包的源文件中写这个,但应该有一个更简单的方法来做到这一点.我不清楚在谷歌中搜索或查找哪些关键词.
无需编辑库。在源文件中,声明:
instance Eq Color where
x == y = fromEnum x == fromEnum y
instance Ord Color where
compare x y = compare (fromEnum x) (fromEnum y)
Run Code Online (Sandbox Code Playgroud)
解释:是一个返回( 、等)fromEnum的函数。整数显然是相等可比较且有序的。EnumintBlack -> 0Red -> 1
编辑:@rampion 的版本,在评论中,显然更漂亮:
instance Eq Color where
(==) = (==) `on` fromEnum
instance Ord Color where
compare = compare `on` fromEnum
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
302 次 |
| 最近记录: |