在Monad.Reader Issue 19 Haskell的游离T和协程型之间的关系,在“协程管道”的文章中,笔者定义了一个通用Coroutine
类型:是什么
newtype Coroutine f m a = Coroutine
{ resume :: m (Either (f (Coroutine f m a)) a)
}
data FreeF f a b = Pure a | Free (f b)
newtype FreeT f m a = FreeT
{ runFreeT :: m (FreeF f a (FreeT f m a))
}
似乎FreeT
和Coroutine
是同构的。下面是一个函数映射到其他:
freeTToCoroutine
:: forall f m a. (Functor f, Functor m) => FreeT f m a -> Coroutine f m a
freeTToCoroutine (FreeT action) = Coroutine $ fmap f action
where
f :: FreeF f a (FreeT f m a) -> Either (f (Coroutine f m a)) a
f (Pure a) = Right a
f (Free inner) = Left $ fmap freeTToCoroutine inner
coroutineToFreeT
:: forall f m a. (Functor f, Functor m) => Coroutine f m a -> FreeT f m a
coroutineToFreeT (Coroutine action) = FreeT $ fmap f action
where
f :: Either (f (Coroutine f m a)) a -> FreeF f a (FreeT f m a)
f (Right a) = Pure a
f (Left inner) = Free $ fmap coroutineToFreeT inner
我有以下问题:
- 什么是
FreeT
和Coroutine
类型之间的关系?为什么“Coroutine Pipelines”的作者没有使用FreeT
类型而不是创建Coroutine
类型? - 自由monads和协程之间有更深的关系吗?这似乎不是巧合,类型是同构的。
为什么在基于
FreeT
的Haskell中不流行的流媒体库?data Proxy a' a b' b m r = Request a' (a -> Proxy a' a b' b m r) | Respond b (b' -> Proxy a' a b' b m r) | M (m (Proxy a' a b' b m r)) | Pure r
data Pipe l i o u m r = HaveOutput (Pipe l i o u m r) (m()) o | NeedInput (i -> Pipe l i o u m r) (u -> Pipe l i o u m r) | Done r | PipeM (m (Pipe l i o u m r)) | Leftover (Pipe l i o u m r) l
我想这将有可能写根据各地
FreeT
的Proxy
或Pipe
数据类型,所以我想知道为什么它没有完成?这是出于性能原因吗?FreeT
我在流行的流媒体库中看到的唯一提示是pipes-group,它使用FreeT
对流中的项目进行分组。
我认为Monad.Reader文章和流式库不使用'FreeT'的原因是一样的:它不会为你赚取任何东西。就文章而言,我认为作者觉得代码更清晰,更独立,正如文章中所显示的那样。在图书馆的情况下,为什么在没有它的情况下完成工作时,为什么会产生对“免费”的依赖(并且在传递上是Kmett平台的一大块)? IOW:是的,'FreeT'确实支持一类协程类型,但这并不意味着一个给定的协程必须使用'FreeT'来实现。无聊的工程问题优先 –
谢谢@BenjaminHodgson。我认为你的评论在回答我的问题1和3方面做得很好。我仍然在思考我的问题2.协程和自由monads之间是否存在某种更深层次的关系? – illabout
对于问题3,我发现了@ gabriel-gonzalez('pipes'的作者)对reddit的感兴趣评论:https://www.reddit.com/r/haskell/comments/23m4bs/i_added_a_coroutine_example_to_the_wiki_did_i/cgyfxux/他说“管道”是相对简单易读的。除了库使用问题之外,这也是'pipes'没有使用密度转换的原因之一。我想这也可能是它不基于'FreeT'的原因之一。没有(?)真正的好处会更难理解。 – illabout