Concerning free software, programming, and whatever else I find interesting. Also the blog for my Web site, frigidcode.com.
haskell: get lines and handle end of file
I thought I'd post this convenience function, since I didn't see an obvious one in base:
Pass in a function which takes a string and does IO. EOF (end of file) causes the loop to stop. Other IO errors are simply raised again. For example:
Permission is given to reuse this code without restriction.
import Prelude hiding (catch) import Control.Exception import System.IO.Error hiding (catch) readl f = catch (getLine >>= return . Just) (\e -> if (isEOFErrorType . ioeGetErrorType) e then return Nothing else ioError e) >>= \a -> case a of Nothing -> return () Just b -> f b >> readl f
main = readl (\x -> putStrLn (x ++ " bleep")) $ ./test.hs hi hi bleep what? what? bleep
Total Comments 0