Word frequency: Difference between revisions

simplify
(simplify)
Line 2,503:
module Main where
 
import DataControl.FunctionMonad ((&)foldM, when)
import Data.FoldableChar (traverse_isSpace, toLower)
import ControlData.MonadList (foldM, when (sortOn, forM_filter)
import Data.Char (isSpace, toLower, isAlpha)
import Data.List (sortOn, foldl', filter)
import Data.Ord (Down(..))
import System.IO (stdin, IOMode(..), openFile, hClose)
Line 2,531 ⟶ 2,529:
main = do
args <- getArgs
when (length args /= 1) (error "expecting 1 arg (number of words to print)")
(n,hand,filep) <- case length args of
let maxw = read $ head args -- no error handling, to simplify the example
0 -> return (10,stdin,False)
T.hGetContents handstdin >>= \contents -> do
1 -> return (read $ head args,stdin,False)
_ -> let (ns:fp:_) = args
in fmap (\h -> (read ns,h,True)) (openFile fp ReadMode)
T.hGetContents hand >>= \contents -> do
freqtable <- frequencies $ filter (not . T.null) $ T.split isSpace $ T.map toLower contents
counts <-
Line 2,542 ⟶ 2,537:
cnt <- readIORef ref
return (w, cnt)
in mapM readRef $ M.toList freqtable
print $ take maxw $ sortOn &(Down mapM. readRefsnd) counts
print $ take 10 $ sortOn (Down . snd) counts
when filep (hClose hand)
</lang>
{{Out}}
Anonymous user