我遇到了一群我想尝试合并的单子。
我使用monad-coroutine,状态和镜头(因为我有深度嵌套状态)。
我有一个初步的方法,那里有一个有效的解决方案。这里的要点是我可以请求在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’
的错误等等......也许其他一些monad堆叠顺序会有所帮助?或者它是否可能?
还有一个问题,如果你有时间:上面的MyType s
和这个之间有什么区别:
type MyType = forall s. Coroutine IORequest (StateT (MyState s) (ST s))