Skip to content

Instantly share code, notes, and snippets.

@afeinberg
Created November 5, 2011 02:58
Show Gist options
  • Save afeinberg/1341029 to your computer and use it in GitHub Desktop.
Save afeinberg/1341029 to your computer and use it in GitHub Desktop.
import Control.Monad
import System.IO
import Data.List
import qualified Data.Map as Map
countWords :: [String] -> Map.Map String Integer
countWords = foldl updateMap Map.empty
where
updateMap m word =
Map.insert word (1 + (Map.findWithDefault 0 word m)) m
mapToSortedList :: (Ord a) => Map.Map k a -> [(k, a)]
mapToSortedList m =
sortBy (\ (_,v1) (_,v2) -> compare v2 v1) (Map.toList m)
readLines :: [String] -> IO [String]
readLines lines =
do
gotEof <- isEOF
if gotEof
then return lines
else
do
line <- getLine
readLines (line : lines)
main :: IO ()
main =
do
lines <- readLines []
let wordMap = countWords . flatten $ lines in
forM_ (mapToSortedList wordMap)
(\ (k, v) -> putStrLn $ k ++ " " ++ (show v))
where
flatten = foldl (\a l -> a ++ words l) []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment