Counting how many times each distinct element in a list occurs

haskell

Solution

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])

Example usage:

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

See documentation of `fromListWith` and `toList`.

Problem

I'm 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 ] ``` Something is wrong with the last part involving `rmdups`. 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 ```

Original source