Skip to content

Instantly share code, notes, and snippets.

@steinfletcher
Last active November 4, 2019 20:35
Show Gist options
  • Save steinfletcher/bec637c2a6d4e6a1d198 to your computer and use it in GitHub Desktop.
Save steinfletcher/bec637c2a6d4e6a1d198 to your computer and use it in GitHub Desktop.
Count words in file in Haskell
import Control.Exception
import System.Environment (getArgs)
catchAny :: IO a -> (SomeException -> IO a) -> IO a
catchAny = Control.Exception.catch
parseArgs :: [a] -> a
parseArgs args
| (length args) == 1 = head args
| otherwise = error "Invalid args. \nUsage: words <file>"
countWords :: String -> Int
countWords inp = sum $ map (length . words) (lines inp)
main :: IO ()
main = do
args <- getArgs
let fileName = parseArgs args
input <- catchAny (readFile fileName) $ \e -> do
error "Could not read file specified"
print $ countWords input
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment