Haskell-计算列表中每个不同元素出现的次数 [英] Haskell - Counting how many times each distinct element in a list occurs
问题描述
我是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屋!