[英]Haskell instance Ord difficulties
我有一个看起来像这样的类型,并且我希望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
[...]
您可以定义一个辅助功能:
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
。 因此,它实际上不是在定义订单,而是在预定订单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.