Reputation: 8043
I have a simple type
data Day = Monday | Tuesday | Wednesday | Thursday | Friday
I'm a newbie in haskell, so I write ==
as follows.
(==) :: Day -> Day -> Bool
Monday == Monday = True
Tuesday == Tuesday = True
Wednesday == Wednesday = True
...
x == y = False
Is there any shorter way to write ==
realization?
Upvotes: 4
Views: 152
Reputation: 2717
You can write
data Day = Monday | Tuesday | Wednesday | Thursday | Friday
deriving Eq
Which will mean that GHC will automatically generate an instance of Eq for Day.
It will generate (==) such that Monday == Monday
, Tuesday == Tuesday
is True
etc, but Monday == Friday
is False
Note that you can't write something like
(==) :: Day -> Day -> Bool
x == x = True
x == y = False
which is perhaps what you were thinking of.
If you try, GHC will complain about conflicting definitions for x.
Upvotes: 6
Reputation: 17136
You can get the compiler to autogenerate these by using the deriving
keyword:
data Day = Monday | Tuesday | Wednesday | Thursday | Friday
deriving Eq
This will define both ==
and /=
for your datatype.
"Eq may be derived for any datatype whose constituents are also instances of Eq." http://www.haskell.org/ghc/docs/7.4.2/html/libraries/base/Data-Eq.html
Upvotes: 12