Skip to content

Instantly share code, notes, and snippets.

@guipn
Last active August 29, 2015 14:02
Show Gist options
  • Save guipn/8d2b02ec9867b7fa7422 to your computer and use it in GitHub Desktop.
Save guipn/8d2b02ec9867b7fa7422 to your computer and use it in GitHub Desktop.
word count
module Main where
import qualified Data.Map as Map
import qualified Data.List as List
import qualified Data.Ord as Ord
main :: IO ()
main = interact $ prettyPrint . toSortedList . counts . List.words
counts :: [String] -> Map.Map String Int
counts = foldr increment Map.empty
increment :: (Integral i) => String -> Map.Map String i -> Map.Map String i
increment s = Map.insertWith (+) s 1
toSortedList :: (Ord i) => Map.Map String i -> [(String, i)]
toSortedList m = List.sortBy (Ord.comparing snd) $ Map.toList m
prettyPrint :: (Show i) => [(String, i)] -> String
prettyPrint = foldr addLine ""
where addLine elem result = result ++ "\n" ++ (fst elem) ++ ": " ++ (show $ snd elem)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment