I want to sort a list of tuples by their second elements.
我想按照第二个元素对元组列表进行排序。
Example input:
示例输入:
[("Bob",3),("Terry",1)]
Example output:
输出示例:
[("Terry",1)("Bob",3)]
3 个解决方案
#1
15
Another cool trick is to use on
from Data.Function:
另一个很酷的技巧是从Data.Function使用on:
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
13
You can use sortBy
and comparing
:
您可以使用sortBy并比较:
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.
在这种情况下,我们想要通过第二个元素进行比较。你可以使用比较snd来获得一个可以通过第二个元素比较两个元组的函数。
#3
2
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
.
这种分类必须使用比较,或其朋友,如<。所以如果你已经实现了这样的事情,那么你可以改为比较(snd a)(snd b)或者snd a snd b而不是仅仅比较b或a 。
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.
sortBy中提供了sortBy,如第三篇所述。
#1
15
Another cool trick is to use on
from Data.Function:
另一个很酷的技巧是从Data.Function使用on:
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
13
You can use sortBy
and comparing
:
您可以使用sortBy并比较:
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.
在这种情况下,我们想要通过第二个元素进行比较。你可以使用比较snd来获得一个可以通过第二个元素比较两个元组的函数。
#3
2
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
.
这种分类必须使用比较,或其朋友,如<。所以如果你已经实现了这样的事情,那么你可以改为比较(snd a)(snd b)或者snd a snd b而不是仅仅比较b或a 。
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.
sortBy中提供了sortBy,如第三篇所述。