在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?
你是对的: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把它放回去.
| 归档时间: |
|
| 查看次数: |
333 次 |
| 最近记录: |