gpt4 book ai didi

haskell - haskell 中如何实现 withFile

转载 作者:行者123 更新时间:2023-12-03 14:26:22 25 4
gpt4 key购买 nike

关注 haskell tutorial ,作者提供了以下实现 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

但是为什么我们需要包装 resultreturn ?不是提供的功能 f已经返回 IO从它的类型可以看出 Handle -> IO a ?

最佳答案

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

withFile' path mode f = do  
handle <- openFile path mode
f handle

不需要退货。问题是 hClose handle介于两者之间,所以我们必须先存储结果:
result <- f handle

和做 <-摆脱 IO .所以 return放回去。

关于haskell - haskell 中如何实现 withFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8567044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com