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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With