使用Haskell排序对对列表进行排序 [英] Sort a list of pairs using sort 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)
区别在于 I have a function (frequency) which that counts how many times each distinct value in a list occurs in that list. For example, should return: This works fine but now I need to sort the list using the first element within the list of the list using this function. example of desired output: The above does not work, I have no idea what I can do. using regular 'sort' Thank you in Advance. Links to documentation for The difference is that 这篇关于使用Haskell排序对对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 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>明确地只查看每一对的第一个元素。
frequency "ababca"
[(3, 'a'), (2, 'b'), (1, 'c')].
results :: [Party ] -> [(Int, Party)]
results xs = ??? frequency (sort xs) ???
[(1, "Green"), (2, "Red"), (3, "Blue")]
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)
on
, sortBy
, compare
, fst
.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.