6

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

Boris
  • 5,094
  • 4
  • 45
  • 71
  • 3
    There is an open ticket to [add source links for instances](http://trac.haskell.org/haddock/ticket/145) in Haddock, which would make finding instances much easier. – hammar May 02 '12 at 14:21
  • Thanks a lot. All good answers, each with a little extra information that makes them stand out from the others. – Boris May 02 '12 at 14:33

3 Answers3

4

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
dave4420
  • 46,404
  • 6
  • 118
  • 152
4

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)
Don Stewart
  • 137,316
  • 36
  • 365
  • 468
4

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.

Chris Kuklewicz
  • 8,123
  • 22
  • 33