具有StateT和ST和IO的协程
在我尝试合并的一组monad中遇到一些麻烦。
我使用monad-coroutine,状态和镜头(因为我有深度嵌套状态)。
我有一个初步的方法,有一个工作解决方案。 这里的要点是我可以请求在协程外执行IO
任务。
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
module Main where
import Control.Monad.Coroutine (Coroutine(..), suspend, resume)
import Control.Monad.State (State, MonadState, MonadIO)
import Control.Monad.State (lift, get, put, liftIO, runState)
import System.Environment (getArgs)
type MyType = Coroutine IORequest (State MyState)
instance (MonadState s m) => MonadState s (Coroutine IORequest m) where
get = lift get
put = lift . put
io :: MonadIO m => IO a -> m a
io = liftIO
data IORequest x = forall a. RunIO (IO a) (a -> x)
instance Functor IORequest where
fmap f (RunIO x g) = RunIO x (f . g)
data MyState = MyState { _someInt :: Int }
initialState :: MyState
initialState = MyState 1
request :: Monad m => IO a -> Coroutine IORequest m a
request x = suspend (RunIO x return)
myLogic :: MyType [String]
myLogic = do
args <- request (io getArgs)
request (io (print args))
-- do a lot of useful stuff here
return args
runMyType :: MyType [String] -> MyState -> IO ()
runMyType logic state = do
let (req, state') = runState (resume logic) state
case req of
Left (RunIO cmd q') -> do
result <- cmd
runMyType (q' result) state'
Right _ -> return ()
main :: IO ()
main = runMyType myLogic initialState
现在,在某个时候,一个简单的国家变得不够了,我需要ST。 我开始试图让ST
内StateT
但由于某种原因不能想出一个点子如何正确处理IO
协同程序之外。 有什么办法拿出类似runMyType
当在一个变化Coroutine
?
type MyType s = Coroutine IORequest (StateT (MyState s) (ST s))
initialState :: ST s (MyState s)
initialState = do
a <- newSTRef 0
return (MyState a)
无论我试着拿出抛出的一些错误s
逃逸或Couldn't match type 's' with 's2'
等等......也许单子堆放的一些其他顺序会有帮助吗? 或者完全有可能?
还有一个问题,如果你有一些时间:上面的MyType s
和这个之间有什么区别:
type MyType = forall s. Coroutine IORequest (StateT (MyState s) (ST s))
链接地址: http://www.djcxy.com/p/53213.html