Skip to content

Instantly share code, notes, and snippets.

@unhammer

unhammer/HTWC.hs Secret

Created May 27, 2022 09:34
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 unhammer/9ec010e9c902d7a08ce3a5b61738197e to your computer and use it in GitHub Desktop.
Save unhammer/9ec010e9c902d7a08ce3a5b61738197e to your computer and use it in GitHub Desktop.
slow :)
{-# LANGUAGE BangPatterns #-}
module Main where
import Control.Monad (when, forM_)
import Data.Char -- toLower, isSpace
import Data.List -- sortBy, (Foldable(foldl')), filter
import Data.Ord -- Down
import System.IO -- stdin, ReadMode, openFile, hClose
import System.Environment -- getArgs
-- hashtables
import Data.HashTable.IO as M
-- text
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
frequencies :: [Text] -> IO (M.BasicHashTable Text Integer)
frequencies t = do
ht <- M.newSized 1500000 -- cheating a bit
forM_ t $ \w -> M.mutate ht w alter
return ht
where
alter Nothing = (Just 1, ())
alter (Just !v) = (Just (1+v), ())
main :: IO ()
main = do
args <- getArgs
(n,hand,filep) <- case length args of
0 -> return (10,stdin,False)
1 -> return (read $ head args,stdin,False)
_ -> let (ns:fp:_) = args
in fmap (\h -> (read ns,h,True)) (openFile fp ReadMode)
T.hGetContents hand >>= \c -> do
freqtable <- frequencies $ filter (not . T.null) $ T.split isSpace $ T.map toLower c
-- for the size hint:
-- print =<< M.foldM (\a _ -> pure $ (a+1::Int)) 0 freqtable
freql <- M.toList freqtable
print (take n $ sortBy (comparing (Down . snd)) freql)
when filep (hClose hand)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment