我有一个看起来像这样的类型,我希望compare
函数只考虑整数的大小。
data Cell = FromLeft Coordinate Int
| FromTop Coordinate Int
| FromDiagonal Coordinate Int
| Empty Coordinate
deriving (Eq, Read, Show)
以下代码有效,但我更喜欢更优雅的内容
instance Ord Cell where
compare (FromLeft _ x) (FromLeft _ y) = compare x y
compare (FromRight _ x) (FromLeft _ y) = compare x y
[...]
答案 0 :(得分:4)
您可以定义辅助功能:
extractInt :: Cell -> Int
extractInt (FromLeft _ x) = x
extractInt (FromTop _ x) = x
extractInt (FromDiagonal _ x) = x
extractInt Empty = ???
然后
instance Ord Cell where
compare c1 c2 = compare (extractInt c1) (extractInt c2)
但要小心:上述情况违反反对称法,该法规定如果x<=y
和y<=x
则x==y
。所以它并不是真正定义订单而是预订。