Haskell gets extra instances for imported data types

I am relatively new to Haskell. I am writing a clone of a card game uno, and I want a pretty colored output of the card. I do

import System.Console.ANSI

which provides

data Color = Black
           | Red
           | Green
           | Yellow
           | Blue
           | Magenta
           | Cyan
           | White
           deriving (Bounded, Enum, Show)

now I want to add the output (Ord, Eq), and I can write it in the source file of the imported package, but there should be an easier way to do this. I don’t know which keywords for Google to look for or search in a book.

+5
source share
1 answer

No need to edit the library. In the source file:

instance Eq Color where
  x == y  =  fromEnum x == fromEnum y

instance Ord Color where
  compare x y  =  compare (fromEnum x) (fromEnum y)

: fromEnum - Enum, int (Black -> 0, Red -> 1 ..). , , .

: @rampion, , :

instance Eq Color where
  (==)  =  (==) `on` fromEnum

instance Ord Color where
  compare  =  compare `on` fromEnum
+4

All Articles