Reputation: 5176
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
:)
Upvotes: 6
Views: 269
Reputation: 8153
The Haskell 98 Report specifies this in section 10.1:
The class methods automatically introduced by derived instances of Eq and Ord are (==), (/=), compare, (<), (<=), (>), (>=), max, and min. The latter seven operators are defined so as to compare their arguments lexicographically with respect to the constructor set given, with earlier constructors in the datatype declaration counting as smaller than later ones.
Derived comparisons always traverse constructors from left to right.
...
All derived operations of class Eq and Ord are strict in both arguments.
Upvotes: 4
Reputation: 137937
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)
Upvotes: 4
Reputation: 47042
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
Upvotes: 4