Haskell实例Ord困难

时间:2016-09-21 14:57:18

标签: haskell types

我有一个看起来像这样的类型,我希望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
  [...]

1 个答案:

答案 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<=yy<=xx==y。所以它并不是真正定义订单而是预订。