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

Adrian Hey ahey at iee.org
Tue Oct 25 07:23:25 EDT 2005


On Tuesday 25 Oct 2005 10:40 am, Charles SDudu wrote:
> Hello, I need to calculate the frequency of each character in a String.

Something like this maybe (untested code ahead)..

import Data.COrdering
import Data.Tree.AVL

calc :: String -> [(Char,Int)]
calc cs = asListL (genAsTree cc [(c,1) | c <- cs])
 where cc (c0,n0) (c1,n1) = 
        case compare c0 c1 of
        LT -> Lt
        GT -> Gt
        EQ -> let n=n0+n1
              in n `seq` Eq (c0,n)

But this uses packages you have to install yourself..
 http://homepages.nildram.co.uk/~ahey/HLibs/Data.COrdering/
 http://homepages.nildram.co.uk/~ahey/HLibs/Data.Tree.AVL/

You could probably do something similar with Data.Map
or Data.IntMap

Regards
--
Adrian Hey



More information about the Haskell-Cafe mailing list