Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between deriving typeclass and creating an instance

Tags:

haskell

Suppose I have this data type:

data TrafficLight = Red | Yellow | Green deriving (Eq)

How is it different from creating an instance of Eq like so:

data TrafficLight = Red | Yellow | Green

instance Eq TrafficLight where
    Red == Red = True  
    Green == Green = True  
    Yellow == Yellow = True  
    _ == _ = False 

What am I missing here?

NOTE

This question is different from the assumed duplicate because I am looking for the contrast between the deriving and instance keyword. The assumed dupe does not mention the instance keyword.

like image 954
dopatraman Avatar asked Jan 28 '16 02:01

dopatraman


1 Answers

You aren't missing anything; deriving is just having the compiler write out the "obvious" instance for you. It doesn't do anything you couldn't do if you wrote out the instance yourself.

The benefits are (1) you don't have to write out the instance and (2) it communicates to anyone reading the source that the instance is the obvious one (rather than having to read the instance definition to determine whether it's non-standard or not).

like image 133
Ben Avatar answered Sep 24 '22 06:09

Ben