Search code examples
haskellhaskell-pipes

In Haskell, how do I promptly close resources?


Old pipes tutorial has following example. How would this code look like with version 4.1.1?

  read' :: FilePath -> Frame Text IO C C ()
  read' file = do
      liftU $ putStrLn "Opening file..."
      h <- liftU $ openFile file ReadMode
      -- The following requires "import qualified Control.Monad as M"
      finallyD (putStrLn "Closing file ..." M.>> hClose h) $ readFile' h

Solution

  • The equivalent function is readFile from Pipes.Safe.Prelude, which you can find here. I've pasted the source below for reference:

    withFile :: MonadSafe m => FilePath -> IO.IOMode -> (IO.Handle -> m r) -> m r
    withFile file ioMode = bracket (liftIO $ IO.openFile file ioMode) (liftIO . IO.hClose)
    
    readFile :: MonadSafe m => FilePath -> Producer' String m ()
    readFile file = withFile file IO.ReadMode P.fromHandle