简体   繁体   中英

Haskell own instance typeclass

I need to declare my own typeclass but I dont understand why there is the (==).

data Egg = Soft | Hard

instance Eq Egg where
(==)

I did not find anything where the (==) is used in an instance, only in a class

The easy way to have an instance of Eq is:

data Egg = Soft | Hard deriving Eq

The hard way (with more control):

data Egg = Soft | Hard

instance Eq Egg where
  Soft == Soft = True
  Hard == Hard = True
  _    == _    = False

UPD : Since the equality function (==) as an operator seem to be the confusing bit, here is the same instance written with a prefix notation:

data Egg = Soft | Hard

instance Eq Egg where
  (==) Soft Soft = True
  (==) Hard Hard = True
  (==) _    _    = False

As a quick reminder: operator are infix (in between terms) by default, and functions are prefix (before terms) by default. To make an operator prefix it is surrounded by () , to make a function infix it is surrounded by `` . Here is a thread talking about which characters are used for operator vs functions.

I assume you're trying to make an instance of the standard typeclass Eq for your custom datatype. The Eq class is defined as:

class Eq a where

  (==) :: a -> a -> Bool
  a == b = not (a /= b)

  (/=) :: a -> a -> Bool
  a /= b = not (a == b)

That is, it defines two methods == and /= (which happen to be operators), and provides default implementations of each one in terms of the other. So to make an instance of Eq for your own type, you need to provide an implementation of one or both of these functions ( == or /= ) for your type. Note that the body of the instance must be indented.

instance Eq Egg where
  Soft == Soft = True
  Hard == Hard = True
  _ == _ = False

Just as you can use a Haskell operator in prefix form by wrapping it in parentheses, eg, (==) 1 1 , you can also implement an operator definition in prefix form:

instance Eq Egg where
  (==) Soft Soft = True
  (==) Hard Hard = True
  (==) _ _ = False

You could even use a case if you so desired:

instance Eq Egg where
  (==) a b = case (a, b) of
    (Soft, Soft) -> True
    (Hard, Hard) -> True
    _ -> False

Note that these are all the same as the instance that would be generated for you automatically with deriving :

data Egg = Soft | Hard
  deriving (Eq)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM