为什么在IO Monad中包含IO结果 [英] Why wrap an IO result in IO Monad

查看:115
本文介绍了为什么在IO Monad中包含IO结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Haskell中,我们有一个函数 readFile :: FilePath - > IO字符串。理解monad时我的问题是为什么将它包装在 IO 中?我们不能只写这样的函数:

 (lines.readFile)path 

而不是

 (readFile> > =行)路径

IO包装提供了什么好处?

解决方案

Haskell表达式是引用透明。这意味着如果 readFile 真的有一个类型的 FilePath - >字符串,则表达式 readFilea.txt总会产生相同的结果。即使你读了文件,然后改变它,然后再读,你会得到它的第一个状态的内容。



因此,我们需要在动作,这就是 IO 的用途。它不会让您在其他表达式中使用结果 readFilea.exe,直到执行与其关联的操作。因此,在更改文件后,必须再次执行读取操作,才能获取文件内容,因此您将能够看到更改。


In Haskell we have a function readFile :: FilePath -> IO String. My question while understanding monad is why wrap it in IO? Couldn't we just have written function like these:

(lines.readFile) path

Rather than

(readFile >>= lines) path 

What benefit does the IO wrapper provide?

解决方案

Haskell expressions are referentially transparent. This means that if readFile would really have a type of FilePath -> String, then expression readFile "a.txt" would always yield the same result. Even if you read the file, then change it, and then read again, you will get the contents in its first state.

Thus, we need to distingush between values and actions, and this is what IO is for. It doesn't let you use the result readFile "a.exe" in other expressions until you perform an action associated with it. As a consequence, after changing your file you have to perform the reading action again, to get file contents, and because of that you will able to see the changes.

这篇关于为什么在IO Monad中包含IO结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆