繁体   English   中英

Haskell实例Ord困难

[英]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<=xx==y 因此,它实际上不是在定义订单,而是在预定订单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM