haskell – GHC.IO的“ioToST”和“unsafeIOToST”有什么区别?


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

-- 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)
安全版本必须从IO monad开始(因为您无法从runST获取ST RealWorld),并允许您在IO上下文和ST RealWorld上下文之间进行切换.它们是安全的,因为ST RealWorld与IO基本相同.

不安全的版本可以从任何地方开始(因为runST可以在任何地方调用),并允许您在任意ST monad和IO monad之间切换.使用runST从一个纯粹的上下文,然后在状态monad中做一个不安全的,基本上等同于使用unsafePerformIO.


转载注明原文:haskell – GHC.IO的“ioToST”和“unsafeIOToST”有什么区别?