forked from benhoyt/countwords
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple.hs
29 lines (25 loc) · 952 Bytes
/
simple.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module CountWords where
import Data.Char (toLower)
import Data.Foldable (Foldable (foldl'))
import Data.List (sortBy)
import qualified Data.Map.Strict as M
import Data.Ord (Down (..), comparing)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import GHC.Unicode (isSpace)
countwords :: Ord a => [a] -> M.Map a Integer
countwords = foldl' (\m k -> M.insertWith (+) k 1 m) M.empty
{-# SPECIALIZE countwords :: [T.Text] -> M.Map T.Text Integer #-}
runCountWords :: IO ()
runCountWords =
T.getContents >>= T.putStrLn
. T.unlines
. map (\(w, i) -> w `T.append` " " `T.append` (T.pack . show $ i))
. sortBy (comparing (Down . snd))
. M.toList
. countwords
. filter (not . T.null)
. T.split isSpace
. T.map toLower