Last active
November 4, 2019 20:35
-
-
Save steinfletcher/bec637c2a6d4e6a1d198 to your computer and use it in GitHub Desktop.
Count words in file in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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