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

Ade*_*ick 5 haskell

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

type Name = String
data ModelNode = NodeAttribute Name | 
                 NodeRelation (Name,Name) |
                 NodeConstraint Name |
                 NodeKPI Name
Run Code Online (Sandbox Code Playgroud)

我需要这种类型的实例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'
Run Code Online (Sandbox Code Playgroud)

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

data ModelNodeType = NodeAttribute | NodeRelation | NodeConstraint | NodeKPI
data ModelNode = ModelNode ModelNodeType Name Maybe Name
Run Code Online (Sandbox Code Playgroud)

毕竟,这在语义上是不正确的.要么

data ModelNodeTypeSingle = NodeAttribute | NodeConstraint | NodeKPI
data ModelNode = ModelNode ModelNodeTypeSingle Name | 
                 ModelNodeRelation (Name,Name)
Run Code Online (Sandbox Code Playgroud)

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

Ørj*_*sen 9

据我所知,你的Ord实例等同于可派生的实例.做就是了

data ModelNode = NodeAttribute Name | 
                 NodeRelation (Name,Name) |
                 NodeConstraint Name |
                 NodeKPI Name
  deriving (Eq,Ord)
Run Code Online (Sandbox Code Playgroud)