views:

157

answers:

3

Suppose I have x :: [(n, a)] where n is a number and a is an unorderable item (is not of class Ord).

I want to sort this list by n.

I cannot do sort x because a is not orderable. I can replace a by indices and then assemble the new list using !! but this seems like a poor solution.

Alternatives?

+11  A: 

Ugh. Never mind. sortBy.

qrest
not just `sortBy` but `sortBy (comparing fst)` (in case you never heard of the `comparing` function).
TomMD
`comparing` is in `Data.Ord`. (But you knew that, because you used hoogle.)
Yitz
[Hoogle](http://haskell.org/hoogle)? Cool, I always just asked Neil Mitchell every time I needed to know where a function was...
TomMD
+4  A: 

You want

sortBy (compare `on` fst)

or something similar. You'll find on defined in module Data.Function, and sortBy in Data.List, which you'll need to import.

Norman Ramsey
Just as a follow up, the more conventional usage is to take advantage of the definition: comparing = on compareNot to contradict the vastly better-skilled Dr. Ramsey, just pointing out a more usual style.
BMeph
@BMpeh don't give me more credit than I'm worth. I learned `on compare` from somebody else and am happy to learn `comparing` from you. (Leaving answer unchanged lest readers become hopelessly confused.)
Norman Ramsey
+2  A: 

Also, if you have an alternate function (e.g., call it f) from which to form an order, you can use the Data.Monoid properties of Ordering:

sortBy (comparing fst `mappend` comparing (f . snd))

which will use your function on the second component of the pair. If you don't need or have a second criterion on which to sort your pairs, then the sortBy (comparing fst) will be just fine (the resulting list will just have pairs with the same first component in list order).

BMeph