dopatraman
dopatraman

Reputation: 13908

Difference between deriving typeclass and creating an instance

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.

Upvotes: 6

Views: 962

Answers (1)

Ben
Ben

Reputation: 71495

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).

Upvotes: 7

Related Questions