[Haskell-cafe] Nice way to calculate character frequency in a string

Scherrer, Chad Chad.Scherrer at pnl.gov
Wed Oct 26 12:50:34 EDT 2005

Sorry to drag this thread out, but here's one more thing you might

I was thinking, if we just wanted something like
intTable :: [Int] -> [(Int, Int)]
we could just replace Map with IntMap in the previous solution:

intTable xs = IntMap.assocs $! foldl' f IntMap.empty xs
    where f m x = let  m' = IntMap.insertWith (+) x 1 m
                       Just v = IntMap.lookup x m'
                  in v `seq` m'

To get another polymorphic version, we could just write this wrapper:

freq :: (Enum a) => [a] -> [(a,Int)]
freq = map fstToEnum . intTable . map fromEnum
    where fstToEnum (x,y) = (toEnum x, y)

This seems to run faster than the other polymorphic version on my

Chad Scherrer
Computational Mathematics Group
Pacific Northwest National Laboratory

"Time flies like an arrow; fruit flies like a banana." -- Groucho Marx

More information about the Haskell-Cafe mailing list