Short == implementation

I have a simple type

data Day = Monday | Tuesday | Wednesday | Thursday | Friday 

I am new to haskell, so I write == as follows.

 (==) :: Day -> Day -> Bool Monday == Monday = True Tuesday == Tuesday = True Wednesday == Wednesday = True ... x == y = False 

Is there a shorter way to implement == implementation?

+4
source share
2 answers

You can force the compiler to auto-generate them using the deriving keyword:

 data Day = Monday | Tuesday | Wednesday | Thursday | Friday deriving Eq 

This will determine both == and /= for your data type.

"Eq can be inferred for any type of data whose components are also instances of the equation" http://www.haskell.org/ghc/docs/7.4.2/html/libraries/base/Data-Eq.html

+12
source

You can write

 data Day = Monday | Tuesday | Wednesday | Thursday | Friday deriving Eq 

This means that the GHC automatically generates an Eq instance for the day. It will generate (==) so that Monday == Monday , Tuesday == Tuesday True , etc., but Monday == Friday - False

Please note that you cannot write something like

 (==) :: Day -> Day -> Bool x == x = True x == y = False 

that maybe what you were thinking about.

If you try, the GHC will complain about conflicting definitions for x.

+6
source

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


All Articles