Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell deriving additional instances for imported datatypes

I'm relatively new to Haskell. I write a clone of the card game uno and i want pretty coloured output of a 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 deriving (Ord, Eq) as well, i could write this in the source file of the imported package, but there should be an easier way to do this. i don't have a clue what keywords to google for or look for in a book.

like image 378
epsilonhalbe Avatar asked Oct 11 '22 04:10

epsilonhalbe


1 Answers

No need to edit the library. In your source file, state:

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

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

Explanation: fromEnum is a function on Enum that returns an int (Black -> 0, Red -> 1, etc.). Integers are obviously equality-comparable and ordered.

Edit: @rampion's version, in the comments, is obviously prettier:

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

instance Ord Color where
  compare  =  compare `on` fromEnum
like image 93
Fred Foo Avatar answered Nov 16 '22 13:11

Fred Foo