[Haskell-beginners] sorting by elements in a tuple

Chaddaï Fouché chaddai.fouche at gmail.com
Fri Oct 16 04:37:38 EDT 2009

On Fri, Oct 16, 2009 at 8:07 AM, Daniel Fischer
<daniel.is.fischer at web.de> wrote:
> 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".

For completeness sake, you can do it like that :

tuplesort = sortBy (comparing fst `mplus` comparing snd)

It's interesting to know how to do it if you want to sort using a
different function than the compare of Ord. The "mplus" use some
instances of Monoid that you'll find in Data.Monoid so don't forget to
import it.


More information about the Beginners mailing list