Skip to content

Instantly share code, notes, and snippets.

@rlupton20
Last active November 18, 2016 08:33
Show Gist options
  • Save rlupton20/86083d2211916075dee94e93e2a4b494 to your computer and use it in GitHub Desktop.
Save rlupton20/86083d2211916075dee94e93e2a4b494 to your computer and use it in GitHub Desktop.
import qualified Data.Map.Strict as M
import Data.List (foldl', sortOn)
-- functors and bind to the rescue!
main :: IO ()
main = fmap countWords getContents >>= putStrLn . show
countWords :: String -> [(String,Integer)]
countWords = sortOn snd . M.toList . foldl' (\m w -> M.insertWith (+) w 1 m) M.empty . words
-- in one line if you really want, though I think it's too long if we're being honest
alternativeMain :: IO ()
alternativeMain = fmap (sortOn snd . M.toList . foldl' (\m w -> M.insertWith (+) w 1 m) M.empty . words) getContents >>= putStrLn . show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment