“基于monad的IO"如何处理?Haskell的设计与基于标记纯/不纯代码的对比? [英] How does the "monad-based IO" design of Haskell contrasts with one based on tagging pure/impure code?

查看:60
本文介绍了“基于monad的IO"如何处理?Haskell的设计与基于标记纯/不纯代码的对比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,IO Monad可以将Haskell中的纯代码与不纯代码分开,从而使类似 f :: ...->的签名成为可能.IO?表示具有副作用的动作,否则为纯函数.

The IO Monad is known to separate pure from impure code in Haskell, such that a signature like f :: ... -> IO ? represents an action with side-effects, otherwise it is a pure function.

此外,在Haskell中,monads被用作一种纯功能机制来对动作进行排序,否则,该行为可能会被设计为仅处理纯函数的编译器意外地重新排序.

In addition, monads are used in Haskell as a purely functional mechanism to sequence actions, which otherwise could be unexpectedly reordered by a compiler that is designed to deal with only pure functions.

围绕monad进行设计的麻烦在于,它们对许多人(包括我自己)似乎很难理解,因此我想知道它们是否是在软件开发中将纯净代码与不纯代码分离的最佳方法.

The trouble with a design around monads is that they seem hard to understand to many, perhaps including myself, so I wonder if they are the best way to separate the pure from impure code in software development.

我假设,如果我们有一种语言,其中所有原语都将被标记为纯净和不纯净,那么编译器可以轻松地直接或间接地使用原语推断任何函数的纯度,这将是一个简单得多的设计.然后,这样的编译器将知道代码的哪些部分可以重新排序,因为它们是纯净的,或者由于存在副作用而需要重新排序.

I suppose that if we had a language where all primitives would be tagged as pure and impure, a compiler could easily infer the purity of any function using the primitives directly or indirectly, which would be a much simpler design. Such compiler would then know which parts of the code could be reordered because they are pure, or some order would be necessary due to the presence of side-effects.

所以,我的问题是:

基于单子的IO"设计与我上面所描述的基于对纯/不纯基元进行标记的语言相比,有哪些优缺点?

What are the advantages/disadvantages of "monad-based IO" design in comparison to one based on tagging pure/impure primitives in the language, that I described above?

推荐答案

Haskell对IO类型进行了类似的操作.但是,Haskell类型系统更为通用.您可以将monad视为潜在副作用范围的声明,因此,除了拥有一个二进制的纯/不纯标志之外,您还可以拥有一个更加复杂的系统.

Haskell does something like this with the IO type. However the Haskell type system is more general. You can think of a monad as a declaration of the potential scope of side effects, so rather than having a binary pure/impure flag you can have a much more sophisticated system.

毫无疑问,Haskell monads是关于杂质"的.IO当然是一种特殊情况,但是其他所有monad都是用Haskell编写的,其中包含"bind"的完美实现.(嗯,也许ST和STM需要运行时系统提供一些魔术来提高效率,但是它们可以用Haskell编写).

Of course its a myth that Haskell monads are about "impurity". IO is a bit of a special case of course, but all the other monads are written in Haskell with a perfectly pure implementation of "bind". (Well, maybe ST and STM need a bit of magic from the run-time system for efficiency, but they could be written in Haskell).

这篇关于“基于monad的IO"如何处理?Haskell的设计与基于标记纯/不纯代码的对比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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