GHC.IO的`ioToST`和`unsafeIOToST`有什么区别? [英] What is the difference between `ioToST` and `unsafeIOToST` from GHC.IO

查看:72
本文介绍了GHC.IO的`ioToST`和`unsafeIOToST`有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 ioToST unsafeSTToIO GHC.IO

   -  ---------------------------------- ----------------------------------------- 

- - IO和ST

- |之间的强制单元变压器在'IO'
- monad中嵌入严格的状态变换器。 'RealWorld'参数表示'ST'计算使用的内部状态
是由'IO'
- monad提供的特殊值,因此与调用'runST'。
stToIO :: ST RealWorld a - > IO a
stToIO(ST m)= IO m

ioToST :: IO a - > ST RealWorld a
ioToST(IO m)=(ST m)

- 这依赖于IO和ST具有相同的表示方式模
- 州
-
unsafeIOToST :: IO a - > ST s a
unsafeIOToST(IO io)= ST $ \\ s - > (unsafeCoerce#io)s

unsafeSTToIO :: ST s a - > IO a
unsafeSTToIO(ST m)= IO(unsafeCoerce#m)


解决方案

安全版本必须从IO monad开始(因为您无法从 runST ST RealWorld c>),并允许您在IO上下文和 ST RealWorld 上下文之间切换。它们是安全的,因为 ST RealWorld 与IO基本上是一样的。



不安全的版本可以在任何地方启动(因为可以在任何地方调用 runST )并允许您在任意ST monad和IO monad之间切换。从纯上下文中使用 runST ,然后在状态monad中执行 unsafeIOToST 基本上相当于使用 unsafePerformIO


What can the differences and intended uses be for ioToST and unsafeSTToIO defined in GHC.IO?

-- ---------------------------------------------------------------------------

-- Coercions between IO and ST

-- | A monad transformer embedding strict state transformers in the 'IO'
-- monad.  The 'RealWorld' parameter indicates that the internal state
-- used by the 'ST' computation is a special one supplied by the 'IO'
-- monad, and thus distinct from those used by invocations of 'runST'.
stToIO        :: ST RealWorld a -> IO a
stToIO (ST m) = IO m

ioToST        :: IO a -> ST RealWorld a
ioToST (IO m) = (ST m)

-- This relies on IO and ST having the same representation modulo the
-- constraint on the type of the state
--
unsafeIOToST        :: IO a -> ST s a
unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s

unsafeSTToIO :: ST s a -> IO a
unsafeSTToIO (ST m) = IO (unsafeCoerce# m)

解决方案

The safe versions must start in the IO monad (because you cannot obtain an ST RealWorld from runST) and allow you to switch between the IO context and a ST RealWorld context. They are safe because ST RealWorld is basically the same thing as IO.

The unsafe versions can start anywhere (because runST can be called anywhere) and allow you to switch between an arbitrary ST monad and the IO monad. Using runST from a pure context and then doing a unsafeIOToST within the state monad is basically equivalent to using unsafePerformIO.

这篇关于GHC.IO的`ioToST`和`unsafeIOToST`有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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