Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - Counting how many times each distinct element in a list occurs

Tags:

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 ]

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

Thank-you in advance.

like image 903
user1353742 Avatar asked May 01 '12 13:05

user1353742


2 Answers

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.

like image 108
Toxaris Avatar answered Sep 16 '22 18:09

Toxaris


I had to use Ord in instead of Eq because of the use of sort

frequency :: Ord a => [a] -> [(Int,a)] 
frequency list = map (\l -> (length l, head l)) (group (sort list))
like image 22
ThePetest Avatar answered Sep 16 '22 18:09

ThePetest