-1

Possible Duplicate:
Counting unique elements in a list
Count frequency of each element in a list

I tried Google, Hoogle, and here and didn't see anything obvious.

It should take ['a', 'b', 'e', 'c', 'e', 'a', 'e'] and return [('a', 2), ('b', 1), ('c', 1), ('e', 3)] or something to that effect.

Community
  • 1
  • 1
Drew
  • 12,578
  • 11
  • 58
  • 98

2 Answers2

6

I would use a Map for counting:

import qualified Data.Map as M

countElems :: (Ord a) => [a] -> M.Map a Int
countElems = M.fromListWith (+) . flip zip (repeat 1)
huon
  • 94,605
  • 21
  • 231
  • 225
ertes
  • 61
  • 1
  • 1
    Every time this question is asked (and I see it all the time), there is this solution and the `group . sort` based solution. I prefer this one for basically no good reason. – luqui Dec 07 '12 at 10:18
2

No. You can use e.g.

import Data.List
import Control.Arrow

map (head &&& length) $ group $ sort ['a', 'b', 'e', 'c', 'e', 'a', 'e']

Or consider using a MultiSet.

luqui
  • 59,485
  • 12
  • 145
  • 204
Landei
  • 54,104
  • 13
  • 100
  • 195