使用Haskell排序对对列表进行排序 [英] Sort a list of pairs using sort Haskell

查看:172
本文介绍了使用Haskell排序对对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数(频率),它计算列表中每个不同值的次数。例如,

 频率ababca

应该返回:

  [(3,'a'),(2,'' b'),(1,'c')]。 

这可以正常工作,但现在我需要使用列表中的第一个元素对列表进行排序使用这个功能。

 结果:: [派对]  - > [(Int,Party)] 
结果xs = ???频率(排序xs)???

所需输出示例:

  [(1,Green),(2,Red),(3,Blue)] 

以上不起作用,我不知道我能做什么。



使用常规'排序'



预先感谢您。

解决方案

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

结果xs = sortBy(比较'fst')(频率xs)

- 或者,如果您更喜欢
结果xs =排序xs)

on sortBy ,< a href =http://www.haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v%3acompare> 比较 fst

区别在于 sort 按照第一个元素的升序排序每对中的第二个元素打破tie-break,而 sortBy(比较`fst) code>明确地只查看每一对的第一个元素。


I have a function (frequency) which that counts how many times each distinct value in a list occurs in that list. For example,

frequency "ababca" 

should return:

[(3, 'a'), (2, 'b'), (1, 'c')].

This works fine but now I need to sort the list using the first element within the list of the list using this function.

results   :: [Party ] -> [(Int, Party)]
results  xs = ??? frequency (sort xs) ??? 

example of desired output:

[(1, "Green"), (2, "Red"), (3, "Blue")]

The above does not work, I have no idea what I can do.

using regular 'sort'

Thank you in Advance.

解决方案

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

results xs = sortBy (compare `on` fst) (frequency xs)

-- or, if you prefer
results xs = sort (frequency xs)

Links to documentation for on, sortBy, compare, fst.

The difference is that sort sorts in ascending order of the first element of each pair, breaking tie-breaks with the second elements of the pairs, while sortBy (compare `on` fst) explicitly only looks at the first element of each pair.

这篇关于使用Haskell排序对对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆