Created
December 30, 2012 20:52
-
-
Save guipn/4415102 to your computer and use it in GitHub Desktop.
Counting occurrences in a list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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