在Haskell中,有没有办法在函数防护中进行IO?
例如:
newfile :: FilePath -> IO Bool
newfile x | length x <= 0 = return False
| doesFileExist x == True = return False
| otherwise = return True
这可以工作吗?
For example:
newfile :: FilePath -> IO Bool
newfile x | length x <= 0 = return False
| doesFileExist x == True = return False
| otherwise = return True
Can this be made to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您已经在
IO
monad 中,那么为什么不使用以下内容呢?对于应用性的好处:
正如您所看到的,应用性路线比您想在问题中使用的防护更加简洁!
You're already in the
IO
monad, so why not use the following?For applicative goodness:
As you can see, the applicative route is even more concise than the guards you'd like to use in your question!
不,没有办法做到这一点(缺少不安全的技巧,这在这里是完全不合适的)。
顺便说一句,如果可能的话,
doesFileExist x == True
最好写成doesFileExist x
。No, there's no way to do this (short of unsafe tricks which would be completely inappropriate here).
BTW
doesFileExist x == True
would be better written asdoesFileExist x
were it possible at all.这有效并完成了所需的操作:
This works and does what's needed:
保护子句的类型必须是
Bool
。doesFileExist x
的类型是IO Bool
。类型不匹配意味着你不能这样做。The type of guard clauses must be
Bool
. The type ofdoesFileExist x
isIO Bool
. The type mismatch means you can't do that.