IO Monad 在什么意义上是纯的? [英] In what sense is the IO Monad pure?

查看:26
本文介绍了IO Monad 在什么意义上是纯的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾将 IO monad 描述为 State monad,其中 state 是现实世界".这种 IO 方法的支持者认为,这使得 IO 操作变得纯粹,就像引用透明一样.这是为什么?从我的角度来看,IO monad 中的代码似乎有很多可观察到的副作用.此外,是否有可能描述几乎任何非纯函数,如现实世界的函数?例如,我们不能把 C 的 malloc 想象成一个接受 RealWorld 和一个 Int 并返回一个指针和一个 RealWorld 的函数,就像在 IO monad 中,RealWorld 是隐式的吗?

I've had the IO monad described to me as a State monad where the state is "the real world". The proponents of this approach to IO argue that this makes IO operations pure, as in referentially transparent. Why is that? From my perspective it appears that code inside the IO monad have plenty of observable side effects. Also, isn't it possible to describe pretty much any non-pure function like a function of the real world? For example, can't we think of, say, C's malloc as being a function that takes a RealWorld and an Int and returns a pointer and a RealWorld, only just like in the IO monad the RealWorld is implicit?

注意:我知道 monad 是什么以及它是如何使用的.请不要回复随机 monad 教程的链接,除非它专门解决了我的问题.

Note: I know what a monad is and how it's used. Please don't respond with a link to a random monad tutorial unless it specifically adresses my question.

推荐答案

我认为我听到的最好的解释实际上是最近关于 SO 的.IO Foo 是创建 Foo 的秘诀.另一种常见的、更直接的说法是,它是一个产生 Foo 的程序".它可以被执行(多次)以创建一个 Foo 或尝试死亡.配方/程序的执行是我们最终想要的(否则,为什么要写一个?),但是在我们的代码中由 IO 操作表示的是配方本身.

I think the best explanation I've heard was actually fairly recently on SO. IO Foo is a recipe for creating a Foo. Another common, more literal, way of saying this is that it is a "program that produces a Foo". It can be executed (many times) to create a Foo or die trying. The execution of the recipe/program is what we ultimately want (otherwise, why write one?), but the thing that is represented by an IO action in our code is the recipe itself.

那个配方是一个纯值,与 String 是一个纯值完全一样.配方可以以有趣的、有时令人惊讶的方式组合和操作,但是这些配方可以通过多种方式组合(除了明显不纯的 unsafePerformIOunsafeCoerce 等.) 都是完全参照透明的、确定性的,以及所有这些好东西.最终的配方绝对不依赖于任何东西的状态,除了它的构建配方.

That recipe is a pure value, in the same exact sense that a String is a pure value. Recipes can be combined and manipulated in interesting, sometimes astonishing, ways, but the many ways these recipes can be combined (except for the blatantly non-pure unsafePerformIO, unsafeCoerce, etc.) are all completely referentially transparent, deterministic, and all that nice stuff. The resulting recipe depends in absolutely no way whatsoever on the state of anything other than the recipes that it was built up from.

这篇关于IO Monad 在什么意义上是纯的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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