Do I need a custom instance of Ord if I have custom Eq?

I had a data type that was used to get general Eqand Ord:

data State = State (Set String) (Set String) deriving (Eq, Ord)

Then I created my own instance Eq:

data State = State (Set String) (Set String) deriving Ord

instance Eq State where
    (State s0 s1) == (State s0' s1') =
        Set.union s0 s1 == Set.union s0' s1'

I'm not sure if this violates the behavior Ordand whether I need to create an instance Ord. Can someone clarify?

+4
source share
1 answer

as I said in my comment, you are breaking the laws Ord:

a :: State
a = State (Set.fromList ["A"]) (Set.fromList ["B"])

b :: State
b = State (Set.fromList ["B"]) (Set.fromList ["A"])     

as of now a == b, as well as a < b:

Ξ»> a == b
True
Ξ»> a < b
True
Ξ»> b < a
False

see: there Ordshould be an entire order , and one of them -

a <b if and only if a ≀ b and a β‰  b

, , :

instance Ord State where
  (State s0 s1) <= (State s0' s1') =
    Set.union s0 s1 <= Set.union s0' s1'

Ξ»> a == b
True
Ξ»> b < a
False
Ξ»> a < b
False
+9

Source: https://habr.com/ru/post/1613774/


All Articles