[Haskell-beginners] sorting by elements in a tuple

Daniel Fischer daniel.is.fischer at web.de
Fri Oct 16 02:07:11 EDT 2009

Am Freitag 16 Oktober 2009 01:19:34 schrieb Ryan Temple:
> I am wanting to sort a list of tuples by the first and then the second item
> in the tuple. So [(1,2),(4,2),(2,5)] would become [(1,2),(2,5),(4,2)]

That's what "sort" already does:

sort [(1,2),(4,2),(2,5),(4,1)] gives [(1,2),(2,5),(4,1),(4,2)]

> I am attempting to use the Sorty function but don't seem to be having much luck
> tuplesort :: [(a,b)] -> [(a,b)]
> tuplesort [(_,_)]

That defines tuplesort on lists containing exactly one pair, probably not what you want.

> = sortBy (comparing fst)

This doesn't conform to the type you gave. "sortBy (comparing fst)" has type

Ord a => [(a,b)] -> [(a,b)]

So your definition of tuplesort has type

Ord a => [(c,d)] -> [(a,b)] -> [(a,b)]

which doesn't look like the type of a sorting function.

> -- this is an attempt to
> organise by the first element in the tuple

You would achieve that by

tuplesort = sortBy (comparing fst)

or, eta-expanded,

tuplesort xs = sortBy (comparing fst) xs

But if you finally want to sort by the second component also (subordinate to sorting by 
the first component), it's much easier to go the whole way at once and use plain "sort".

> Any help would be much appreciated

More information about the Beginners mailing list