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

Pedro Baltazar Vasconcelos pbv at dcc.fc.up.pt
Tue Oct 25 05:34:40 EDT 2005


Two solutions using immutable and mutable arrays and no unsafe operations:

----
module Main where
import Control.Monad.ST
import Data.Ix
import Data.Array
import Data.Array.MArray
import Data.Array.ST


-- using immutable arrays
hist1 :: String -> Array Char Int
hist1 str = accumArray (+) 0 ('\0','\255') [(c,1) | c<-str]
 

freq1 :: String -> [(Char,Int)]
freq1 = assocs . hist1


-- using mutable ST arrays
hist2 :: String -> STArray s Char Int -> ST s ()
hist2 str arr = sequence_ [do { i<-readArray arr c; writeArray arr c (1+i) }
                          | c<-str]

freq2 :: String -> [(Char,Int)]
freq2 str = runST (do { arr<-newArray ('\0', '\255') 0
                      ; hist2 str arr
                      ; getAssocs arr
                      })

--

Cheers,

Pedro


More information about the Haskell-Cafe mailing list