我想要按照元组的第二个元素对列表进行排序。
示例输入:
示例输入:
[("Bob",3),("Terry",1)]
示例输出:
[("Terry",1)("Bob",3)]
另一个很酷的技巧是使用Data.Function中的on
:
import Data.Function (on)
import Data.List (sortBy)
sortBy (compare `on` snd) [...]
与比较
没什么不同,但偶尔可以用一个好技巧。
on
有一些不错的技巧。我偶尔会发现equating = on (==)
很有用。(comparing = on compare
) - Dan BurtonmyFancySort = {- 在这里使用ehird的提示进行实现 -}
。 - Daniel Wagnersort xs = ... a < b ...
这样的排序必须使用compare
或其相关函数,如<
。因此,如果您已经实现了这样的功能,那么您可以使用compare (snd a) (snd b)
或snd a < snd b
代替简单的compare a b
或a < b
。
sort xs = ... snd a < snd b ...
sortComparingOn f xs = ... f a < f b ...
sortBy cmp xs = ... a `cmp` b ...
sortBy
是在 Data.List 中提供的,正如 ehird 所提到的。