haskell - 在实现 MonadIO 的 Monad 中嵌入异步

标签 haskell haskell-pipes

我有一些 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 return MonadIO m => m () and async requires IO 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/

相关文章:

string - 使用 Haskell 将字符串拆分为列表

haskell - Haskell 中可疑的 'Int' 与 'Integer' 处理?

list - 在线性时间内反转排列,仅使用列表

Haskell Pipes——让管道消耗它产生的东西(本身)

haskell - 如何将 Maybe 值注入(inject) MaybeT

haskell - 是否可以反转显示的顺序错误?

haskell - 流媒体库中惯用的预取

http - 我怎么知道在我的 Haskell 程序中哪里可以抛出异常?

haskell - 使用管道 4.0 折叠流的子集

haskell - 由内而外构建管道代理