[Haskell-beginners] List.sort

John Dorsey haskell at colquitt.org
Sat Jul 11 09:17:04 EDT 2009


I sent this only to Patrick by mistake.  Sorry for the duplicate, Patrick.

--

Patrick,

>   Ord a => [a] -> [a]
> 
> I don't understand how this type can allow it to sort pairs:
> 
> Prelude> :m +List
> Prelude List> sort [(1, "1"), (3, "3"), (2, "2")]
> [(1,"1"),(2,"2"),(3,"3")]
> 
> How can a pair by of type "Ord a"? Is it a rule that the first element
> is automatically used?

"Ord a" isn't really the type of a pair... it's a type *constraint* on the
argument to the sort function, which is otherwise any type "a".

So it means List.sort can be applied to any type "a" which satisfies "Ord a".  
But what does that mean?  It means that there is an instance for the
typeclass Ord for whatever type is given to Listsort.

In the case of pairs, it's exactly as you guessed... the leftmost parts are
compared first.  This is so because somewhere there's an "instance Ord (a,b)"
that defines how to compare pairs, and it does it that way (left-to-right).
(And this generalizes to tuples bigger than pairs, up to some
compiler-specific limit.)

Does this make sense?

John



More information about the Beginners mailing list