大多数发生在列表中

编程入门 行业动态 更新时间:2024-10-27 02:19:08
本文介绍了大多数发生在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个高阶函数,需要:

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

从排序的频率列表中.

更多推荐

大多数发生在列表中

本文发布于:2023-07-24 13:25:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1203707.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发生在   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!