大多数发生在列表中 [英] Most occurred within a list
问题描述
我有一个高阶函数,需要:
I have a high order function which would take:
results ["Red", "Blue", "Green", "Blue", "Blue", "Red"]
并返回:
[(1,"Green"),(2,"Red"),(3,"Blue")]
我需要使用results函数并创建一个名为Winner的新函数:
I need to use the results function and create a new function called winner:
winner :: [Party ] -> Party
winner xs =
将输出出现最多的颜色并删除元组中的第一个元素,如果两种颜色出现的相同,则输出两种颜色,例如:
which would output the most occurred colour and remove first element within tuples, if two colours have the same occurrences it output two the colours, for example:
winner ["Red", "Blue", "Green", "Blue", "Blue", "Red"]
输出:
"blue"
到目前为止,我已经尝试使用snd和tail,但是我一直遇到错误. 先感谢您.
so far I've tried using snd and tail but I keep getting errors. Thank you in advance.
推荐答案
如果您具有results
函数,则是一个简单的应用程序
If you have the results
function, a simple application of
maximumBy :: (a -> a -> Ordering) -> [a] -> a
足够了
import Data.List -- for maximumBy
import Data.Ord -- for comparing
winner = snd . maximumBy (comparing fst) . results
看见
如果两种颜色出现的次数相同,则会输出两种颜色
if two colours have the same occurrences it output two the colours
您需要一个不同的类型-当然需要一个不同的实现,但是使用库函数仍然很容易:
you need a different type - and of course a different implementation, still easy with library functions, though:
import Data.List
import Data.Ord
import Data.Function
winners :: [Party] -> [Party]
winners = map snd . head . groupBy ((==) `on` fst) . sortBy (flip $ comparing fst) . results
由于results
已经产生了一个排序列表-我不想仅依赖示例输出中的列表-无需再次排序,我们可以使用
Since results
already produces a sorted list - I didn't want to rely on that just from the example output - it is not necessary to sort again, and we can use
winners = map snd . last . groupBy ((==) `on` fst) . results
生成所有最常出现的元素的列表.如果只需要一个最频繁的元素,则可以使用
to produce the list of all most occurring elements. If only one most frequent element is desired, it could be obtained with
winner = snd . last . results
从排序的频率列表中.
这篇关于大多数发生在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!