Created
November 5, 2011 02:58
-
-
Save afeinberg/1341029 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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