Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source code for standard typeclass instance declarations

I was wondering about the Ord instance declaration for (a,b), and I wanted to do a quick lookup on hackage to confirm my intuition that the comparison is first on a and then, in case of equality, on b. Specifically I went here. Since hackage has links to the source code for data declarations and functions, I assumed that there would also be source code for instance declarations, but I can't find them. Is there a reason why they are not there, or have I just not looked hard enough? type Answer = Either Explanation Directions :)

like image 780
Boris Avatar asked May 02 '12 12:05

Boris


2 Answers

I went looking in the Prelude, clicked on the source link for the Ord typeclass, scrolled down a little, and found that it's defined as

deriving instance (Ord a, Ord b) => Ord (a, b)

It's using the StandaloneDeriving extension. Basically it's generating the same code as if the type was defined as

data (a, b) = (a, b) deriving Ord
like image 129
dave4420 Avatar answered Sep 21 '22 12:09

dave4420


The Ord instance for tuples is derived, according to the rules from the language specification, which goes back as far as Gofer.

instance (Eq a, Eq b) => Eq (a,b) where
    (x,y) == (u,v)  =  x==u && y==v

instance (Ord a, Ord b) => Ord (a,b) where
    (x,y) <= (u,v)  = x<u  ||  (x==u && y<=v)
like image 22
Don Stewart Avatar answered Sep 19 '22 12:09

Don Stewart