Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumbersome Ord implementation for a custom data type

Tags:

haskell

I've created a data type in Haskell:

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

And I need this type to be an instance of Ord. The implementation I came up with is:

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'

Which looks a bit cumbersome to me in the elegant and concise Haskell world. Is there any trick/syntax rule to make it simpler? Or should I redesign my data type to something like:

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

which is, after all, not semantically correct. Or

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

which simplifies the implementation of Ord, but the data type itself becomes less readable?

like image 516
AdelNick Avatar asked Jul 04 '14 10:07

AdelNick


1 Answers

As far as I can tell, your Ord instance is equivalent to the derivable one. Just do

data ModelNode = NodeAttribute Name | 
                 NodeRelation (Name,Name) |
                 NodeConstraint Name |
                 NodeKPI Name
  deriving (Eq,Ord)
like image 187
Ørjan Johansen Avatar answered Oct 04 '22 13:10

Ørjan Johansen