Skip to content

Instantly share code, notes, and snippets.

@guipn
Created December 30, 2012 20:52
Show Gist options
  • Save guipn/4415102 to your computer and use it in GitHub Desktop.
Save guipn/4415102 to your computer and use it in GitHub Desktop.
Counting occurrences in a list
import Data.List
count :: (Eq a, Ord a) => [a] -> [(a, Int)]
count = map wrap . group . sort
where wrap g = (head g, length g)
----------------------------------------
increment :: (Eq a) => [(a, Int)] -> a -> [(a, Int)]
increment counts elt | lookup elt counts == Nothing = (elt, 1) : counts
| otherwise = map incIfTarget counts
where incIfTarget (x, count) | x == elt = (x, count + 1)
| otherwise = (x, count)
count :: (Eq a) => [a] -> [(a, Int)]
count = foldl increment []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment