Skip to content

Instantly share code, notes, and snippets.

@Decoherence
Last active August 29, 2015 14:11
Show Gist options
  • Save Decoherence/954e2556f53828fd3105 to your computer and use it in GitHub Desktop.
Save Decoherence/954e2556f53828fd3105 to your computer and use it in GitHub Desktop.
Haskell: Frequency count for randomly generated letters
import Control.Monad
import System.Random
import Data.List
import Data.Ord
-- Letters of the alphabet
alpha = ['a'..'z']
-- Get a random letter
rLetter = randomRIO (0,25) >>= return . (!!) alpha
-- Frequency count:
-- Sort letters in order, group together identical letters, then return a tuple containing (letter, frequency)
freq = map (\l -> (head l, length l)) . group . sort
-- Generate 10,000 random letters, sorted by most frequent
main :: IO [(Char, Int)]
main = return . reverse . (sortBy (comparing snd)) . freq =<< replicateM 10000 rLetter
{-
OUTPUT:
λ main
[('c',424),('h',412),('o',408),('m',406),('w',402),('y',400),('p',398),('j',393),('x',392),('s',390),('l',389),('z',388),('u',386),('k',386),('i',386),('e',384),('d',378),('v',376),('a',374),('q',367),('b',366),('f',365),('n',363),('g',359),('t',354),('r',354)]
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment