Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell sorting of an unorderable list using a proxy order

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?

like image 789
qrest Avatar asked Jul 05 '10 06:07

qrest


3 Answers

Ugh. Never mind. sortBy.

like image 146
qrest Avatar answered Nov 12 '22 05:11

qrest


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.

like image 45
Norman Ramsey Avatar answered Nov 12 '22 05:11

Norman Ramsey


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

like image 2
BMeph Avatar answered Nov 12 '22 04:11

BMeph