Haskell-计算列表中每个不同元素出现的次数 [英] Haskell - Counting how many times each distinct element in a list occurs

查看:424
本文介绍了Haskell-计算列表中每个不同元素出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Haskell的新手,我只是想编写一个列表理解来计算列表中每个不同值的出现频率,但最后一部分却遇到了麻烦.

I'm new to Haskell and am just trying to write a list comprehension to calculate the frequency of each distinct value in a list, but I'm having trouble with the last part..

到目前为止,我有这个:

So far i have this:

frequency :: Eq a => [a] -> [(Int,a)] 
frequency list = [(count y list,y) | y <- rmdups ]

涉及rmdups的最后一部分出了问题.

Something is wrong with the last part involving rmdups.

count函数先获取一个字符,然后获取一个字符列表,并告诉您该字符出现的频率,代码如下.

The count function takes a character and then a list of characters and tells you how often that character occurs, the code is as follows..

count :: Eq a => a -> [a] -> Int
count x [] = 0
count x (y:ys) | x==y = 1+(count x ys)
               | otherwise = count x ys

先谢谢您.

推荐答案

在计算频率时,您还可以使用关联数组/有限映射存储从列表元素到其计数的关联:

You could also use a associative array / finite map to store the associations from list elements to their count while you compute the frequencies:

import Data.Map (fromListWith, toList)

frequency :: (Ord a) => [a] -> [(a, Int)]
frequency xs = toList (fromListWith (+) [(x, 1) | x <- xs])

示例用法:

> frequency "hello world"
[(' ',1),('d',1),('e',1),('h',1),('l',3),('o',2),('r',1),('w',1)]

请参见 fromListWith 的文档代码> toList .

See documentation of fromListWith and toList.

这篇关于Haskell-计算列表中每个不同元素出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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