Creating a custom data type

Can someone explain to me how to make a custom data type valid?

** I am not allowed to make changes to the Costume itself, for example. (Eq, Ord)

data Suit = Clubs | Diamonds | Hearts | Spades deriving (Eq) 

My attempt:

 instance Ord Suit where compare suit1 suit2 = compare suit1 suit2 

but it looks like a continuous cycle and does not stop.

+7
source share
3 answers

The definition of Ord looks something like this (but not quite)

 class Ord a where compare :: a -> a -> Ordering 

and Ordering has three possible values: LT, EQ, GT .

So, you need to determine what the result of each comparison should be. Something like:

 instance Ord Suit where compare Clubs Diamonds = LT compare Diamonds Clubs = GT compare Diamonds Diamonds = EQ compare Diamonds _ = LT -- Diamonds are lower than everything besides Clubs and Diamonds 

Your actual order may be different, but this should give you the basic idea.

+8
source

You can use offline receive with the same effect.

 deriving instance Enum Suit deriving instance Ord Suit 
+4
source

A way to write a custom instance of Ord , where you do not need to specify the result of each comparison:

 instance Ord Suit where compare ab = compare (relativeRank a) (relativeRank b) where relativeRank Diamonds = 1 relativeRank Clubs = 2 relativeRank Hearts = 3 relativeRank Spades = 4 

Here you only need to specify each constructor once, and you can easily choose a different order.

You can simply use compare Data.Function.on relativeRank , but this may be easier to understand.

+3
source

All Articles