Skip to content

Instantly share code, notes, and snippets.

@andrewhavck
Created June 11, 2010 19:41
Show Gist options
  • Save andrewhavck/434938 to your computer and use it in GitHub Desktop.
Save andrewhavck/434938 to your computer and use it in GitHub Desktop.
-- file:HuffmanEncoding/Frequency.hs
module Frequency where
import Data.List(nub,foldl')
frequencies :: (Eq a) => [a] -> [(a, Double)]
frequencies s = zip (nub s) (map divide qset)
where divide (_,d) = (d / (total qset))
qset = quantities (nub s) s
total :: [(a,Double)] -> Double
total xs = foldl' step 0 xs
where step acc (_,d) = acc + d
quantities :: (Eq a) => [a] -> [a] -> [(a, Double)]
quantities ls xs = foldr ((:) . step) [] ls
where step l = (l, quantity l xs)
quantity :: (Eq a) => a -> [a] -> Double
quantity s xs = foldl' step 0 xs
where step acc x | x == s = 1 + acc
| otherwise = acc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment