Skip to content

Instantly share code, notes, and snippets.

@fcamel
Created June 9, 2009 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcamel/126511 to your computer and use it in GitHub Desktop.
Save fcamel/126511 to your computer and use it in GitHub Desktop.
--
-- wc.hs: word count
--
-- Given a file name in the first command line argument,
-- print WORD: COUNT for each WORD per line.
-- The output is ordred by COUNT.
--
import System
import Data.List
import Data.Function
count :: [String] -> [(String, Int)]
count line = map count' $ group $ sort line
where count' xs = (head xs, length xs)
sortedCount :: [String] -> [(String, Int)]
sortedCount line = sortBy (compare `on` snd) $ count line
main = do
args <- getArgs
content <- readFile (head args)
let inputWords = concat $ map words $ lines content
let results = [w ++ ": " ++ show n | (w, n) <- sortedCount inputWords]
sequence_ (map putStrLn results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment