我有一些 pipes-concurrency
代码,如下所示:
-- this won't compile but will give you the gist of what's happening
pipeline :: MonadIO m => Consumer a m ()
main = do
(output, input) <- spawn Unbounded
async $ do runEffect $ fromInput input >-> pipeline
performGC
-- skipped the `output` pipeline code.
问题 1:这显然无法编译,因为 runEffect
将返回 MonadIO m => m ()
和 async
需要 IO a
。有没有办法做到这一点?还是我一直在强制我的管道在 IO monad 中包含效果?
问题 2:在实现 MonadIO 的 Monad 中嵌入异步是否有意义?不确定我在这里是否表达得很好。
谢谢!
最佳答案
This obviously won't compile since
runEffect
will returnMonadIO m => m ()
and async requiresIO a
这不太对。 IO
是 MonadIO
的实例,因此您的 runEffect
的输出可以传递给 async
或者例如一个接受 MaybeT IO ()
的函数(也是一个 MonadIO
实例)。
我想你要找的是 liftIO :: IO a -> m a
,这将使您将 async
返回的特定 IO (Async a)
“提升”为您的类型中要求的多态 MonadIO
类型签名。
...
liftIO $ async $ do runEffect $ fromInput input >-> pipeline
performGC
还没有尝试编译它;您可能还需要提升函数的其他 IO
部分。
Question 2: does it even make sense to embed an async within a Monad implementing MonadIO? Not sure if I'm articulating myself well here.
当然,如果你想在一些 monad 堆栈中进行并发,为什么不呢?
关于haskell - 在实现 MonadIO 的 Monad 中嵌入异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090772/