有没有办法在纯函数中放置一些不纯的代码? [英] Is there a way to place some impure code inside pure functions?
问题描述
IO
,就像Maybe
一样,只是Monad
的一个实例.另一方面,我们有 Maybe
(Just
和 Nothing
)的所有数据构造函数,但没有 IO
的构造函数.Reader
和 Writer
也不导出构造函数,它们有函数,返回该类型的实例(reader
和 writer
>) 以及更重要的 runReader
和 runWriter
,它们解开 Monad 的计算结果.
IO
, just like Maybe
, is just an instance of Monad
. On the other hand we have all data constructors for Maybe
(Just
and Nothing
), but no constructors for IO
. Reader
and Writer
do not export constructors too, they have functions, which return instance of this type (reader
and writer
) and more importantly runReader
and runWriter
, which unwrap computation result from Monad.
有没有办法解开 IO Monad?我想要纯函数,它在幕后做一些不纯的 IO 计算.目前我可以用大多数 Monads 做到这一点
Is there a way to unwrap IO Monad? I would like to have pure function which do some impure IO computations under the hood. Currently I am able to do this with most of the Monads
我知道一个这样棘手的函数的例子:Debug.Trace.trace
I know one example of such tricky function: Debug.Trace.trace
推荐答案
unsafePerformIO :: IO a ->
.System.IO.Unsafe
(基础)中的一个
unsafePerformIO :: IO a -> a
in System.IO.Unsafe
(base).
谨慎使用并阅读文档 仔细.
Use it with caution and read the description in the documentation carefully.
这篇关于有没有办法在纯函数中放置一些不纯的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!