I am wondering if there is a way to count the distinct elements in a list and group the counts into tuples, for example
[4,4,4,2,2,2,2,1,1,3]
or
[4,2,4,4,2,1,2,2,1,3]
would yield
[(4,3),(2,4),(1,2),(3,1)]
while preserving the order of the original list.
This question mentions preserving the order in the comments, but never addresses the issue.
Here is my attempt thus far:
import Data.List (nub)
countOccurance :: (Eq a) => a -> [a] -> Int
countOccurance x = length . filter (==x)
naiveCounter :: (Eq a) => [a] -> [(a, Int)]
naiveCounter l = map (\x -> (x, countOccurance x l)) $ nub l
but this seems quite inefficient. Is there a way to construct this more efficiently (for instance, by traversing the list only one time)?
Thanks.