自定义数据类型的繁琐Ord实现

时间:2014-07-04 10:25:40

标签: haskell

我在Haskell中创建了一种数据类型:

type Name = String
data ModelNode = NodeAttribute Name | 
                 NodeRelation (Name,Name) |
                 NodeConstraint Name |
                 NodeKPI Name

我需要此类型作为Ord的实例。我想出的实现是:

instance Ord ModelNodeKind where
    compare (NodeAttribute n)  (NodeAttribute n') = compare n n'
    compare (NodeAttribute _)  _                  = LT
    compare _                  (NodeAttribute _)  = GT
    compare (NodeRelation n)   (NodeRelation n')  = compare n n'
    compare (NodeRelation _)   _                  = LT
    compare _                  (NodeRelation _)   = GT
    compare (NodeConstraint n) (NodeConstraint n')= compare n n'
    compare (NodeConstraint _) _                  = LT
    compare _                  (NodeConstraint _) = GT
    compare (NodeKPI n)        (NodeKPI n')       = compare n n'

在优雅简洁的Haskell世界中,这看起来有点麻烦。是否有任何技巧/语法规则使其更简单?或者我应该将我的数据类型重新设计为:

data ModelNodeType = NodeAttribute | NodeRelation | NodeConstraint | NodeKPI
data ModelNode = ModelNode ModelNodeType Name Maybe Name

毕竟,这在语义上是不正确的。或

data ModelNodeTypeSingle = NodeAttribute | NodeConstraint | NodeKPI
data ModelNode = ModelNode ModelNodeTypeSingle Name | 
                 ModelNodeRelation (Name,Name)

简化了Ord的实现,但数据类型本身变得不那么可读了?

1 个答案:

答案 0 :(得分:9)

据我所知,您的Ord实例等同于可派生实例。只是做

data ModelNode = NodeAttribute Name | 
                 NodeRelation (Name,Name) |
                 NodeConstraint Name |
                 NodeKPI Name
  deriving (Eq,Ord)