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?
Ugh. Never mind. sortBy
.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With