How to implement "Ord" for algebraic data types in Haskell?

The best way would be to just add deriving (Eq, Ord) to the type's definition.

Since you listed your constructors in ascending order, the derived Ord instance will give you exactly the order you want.

However, if changing the order in the definition is not an option for some reason you can still derive Eq, since for that the order does not matter. Given an instance of Eq, we can manually write an instance for Ord. The most succinct way to define compare would probably be to spell out all the combinations for which compare should return LT and then simply use compare x y | x == y = Eq; compare _ _ = GT for the remaining combinations.


As has been mention, you can derive Eq and Ord. Or you could derive Enum and then do

instance Eq Rating where
    x == y = fromEnum x == fromEnum y

Or just spell it all out

instance Eq Rating where
    OneStar == OneStar = True
    TwoStar == TwoStar = True
...
    _ == _ = False

Tags:

Haskell