在Haskell中,如何及时关闭资源?

时间:2014-04-19 18:41:13

标签: haskell haskell-pipes

pipes tutorial有以下示例。这个代码在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

1 个答案:

答案 0 :(得分:2)

readFile的等效函数为Pipes.Safe.Prelude,您可以找到here。我已将以下来源粘贴参考:

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