如何在haskell中实现withFile

And*_*yuk 5 haskell

haskell教程之后,作者提供了withFile方法的以下实现:

withFile' :: FilePath -> IOMode -> (Handle -> IO a) -> IO a  
withFile' path mode f = do  
    handle <- openFile path mode   
    result <- f handle  
    hClose handle  
    return result  
Run Code Online (Sandbox Code Playgroud)

但是,为什么我们需要包裹result在一个return?提供的功能是否f已经返回,IO因为它的类型可以看出Handle -> IO a

Owe*_*wen 7

你是对的:f已经返回一个IO,所以如果函数是这样编写的:

withFile' path mode f = do  
    handle <- openFile path mode   
    f handle
Run Code Online (Sandbox Code Playgroud)

没有必要返回.问题出hClose handle在两者之间,所以我们必须先存储结果:

result <- f handle
Run Code Online (Sandbox Code Playgroud)

并做了<-摆脱IO.所以return把它放回去.

  • @delnan那将是`do {handle < - openFile模式路径; hClose句柄; f手柄; ``,所以`f handle`可能会抱怨关闭句柄. (3认同)