0
votes
class  Eq a  where
    (==), (/=)           :: a -> a -> Bool
    x /= y               = not (x == y)
    x == y               = not (x /= y)

deriving instance Eq Bool

I assume it generates

instance Eq Bool where
    True == True = True
    False == False = True

But how do I create a instance from something like

newtype Sink p = Sink {unSink :: MVar (E.Iteratee (Message p) IO ())}

instance Eq (Sink p) where
 ?==? = True

Do I just use deriving and ghc will figure out itself?

deriving instance Eq (Sink p)

http://hackage.haskell.org/packages/archive/websockets/0.7.0.0/doc/html/src/Network-WebSockets-Monad.html#Sink

PS I have read this but it goes beyond my capabilities of understanding http://www.haskell.org/ghc/docs/7.6.1/html/users_guide/deriving.html

2
no, I could not imagine it would work :) - Gert Cuykens
After testing newtype Sink p = Sink {unSink :: MVar (E.Iteratee (Message p) IO ())} deriving (Eq) works because every socket has a different MVar - Gert Cuykens

2 Answers

5
votes

Yes, that will work since there is an instance Eq (MVar a) that tests whether to MVars are the same [1]. The derived instance for Sink will use that. However this might not be what you want since the Eq instance doesn't compare the contents of the MVars, only whether they are the same MVar in memory.

The answer to your question

But how do I create a instance from something like ... Do I just use deriving and ghc will figure out itself?

is probably "No, you must write an instance that has the properties that you want."

4
votes

For Bool the instance actually reads

True  == True  = True
False == False = True
_     == _     = False

of course.

For a description of how deriving instances works in the general case, see Chapter 10 of the Haskell Report.

For your example type, an instance declaration equivalent to what would be derived is—straightforwardly—

instance Eq (Sink p) where
  Sink var == Sink var' = var == var'

Hence, as the type of websocket sinks is isomorphic to a certain instantiation of the type of mutable variables, comparing two sinks reduces two comparing two mutable variables.