How does the “monad-based IO” design of Haskell contrasts with one based on tagging pure/impure code?

妖精的绣舞 提交于 2021-01-29 02:37:58

问题


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.

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.

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.

So, my question is:

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?


回答1:


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.

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).



来源:https://stackoverflow.com/questions/32569852/how-does-the-monad-based-io-design-of-haskell-contrasts-with-one-based-on-tagg

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!