Sort a list of tuples by their second elements

耗尽温柔 提交于 2019-11-30 23:16:26

问题


I want to sort a list of tuples by their second elements.

Example input:

[("Bob",3),("Terry",1)]

Example output:

[("Terry",1)("Bob",3)]

回答1:


Another cool trick is to use on from Data.Function:

import Data.Function (on)
import Data.List (sortBy)

sortBy (compare `on` snd) [...]

Not much different than comparing but a nice trick from time to time.




回答2:


You can use sortBy and comparing:

sortBy :: (a -> a -> Ordering) -> [a] -> [a]
comparing :: (Ord b) => (a -> b) -> a -> a -> Ordering

In this case, we want to compare by the second element. You can use comparing snd to get a function that can compare two tuples by their second element.




回答3:


Consider a "regular" sort

sort xs = ... a < b ...

Such sorts must make use of compare, or its friends such as <. So if you have implemented such a thing already, then instead of just compare a b or a < b, you can instead do compare (snd a) (snd b) or snd a < snd b.

sort xs = ... snd a < snd b ...

Of course if you get smart, you'll abstract out the "accessor", and make it an additional input to the sorting function:

sortComparingOn f xs = ... f a < f b ...

You might even abstract out the comparator altogether:

sortBy cmp xs = ... a `cmp` b ...

sortBy is provided in Data.List, as ehird mentioned.



来源:https://stackoverflow.com/questions/9319133/sort-a-list-of-tuples-by-their-second-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!