开发者

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 lis开发者_运维问答t 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜