Haskell streaming line reader with foldLinesM
Haskell
import System.IO (IOMode (ReadMode), hGetLine, hIsEOF, withFile)
foldLinesM :: (a -> String -> IO a) -> a -> FilePath -> IO a
foldLinesM step seed path = withFile path ReadMode (go seed)
where
go acc h = do
done <- hIsEOF h
if done
then pure acc
else hGetLine h >>= step acc >>= flip go h
forEachLine :: FilePath -> (String -> IO ()) -> IO ()
forEachLine path act = foldLinesM (const act) () path