【问题标题】:Why can't Conduit and Pipe have an Arrow instance?为什么 Conduit 和 Pipe 不能有 Arrow 实例?
【发布时间】:2017-02-23 14:41:46
【问题描述】:

reddit 上有一个存档线程,它说基本上导管/管道不能是箭头 b/c 箭头需要同步。帖子链接在这里https://www.reddit.com/r/haskell/comments/rq1q5/conduitssinks_and_refactoring_arrows/

我看不到“同步”的来源,因为这不是箭头定义的一部分。另外,我在 github https://github.com/cmahon/interactive-brokers 上偶然发现了这个项目,它明确地将管道视为箭头。为了您的方便,我将实例 def 粘贴在这里。我在这里错过了什么?

-- The code in this module was provided by Gabriel Gonzalez

{-# LANGUAGE RankNTypes #-}

module Pipes.Edge where

import           Control.Arrow
import           Control.Category (Category((.), id))
import           Control.Monad ((>=>))
import           Control.Monad.Trans.State.Strict (get, put)
import           Pipes
import           Pipes.Core (request, respond, (\>\), (/>/), push, (>~>))
import           Pipes.Internal (unsafeHoist)
import           Pipes.Lift (evalStateP)
import           Prelude hiding ((.), id)

newtype Edge m r a b = Edge { unEdge :: a -> Pipe a b m r }

instance (Monad m) => Category (Edge m r) where
    id  = Edge push
    (Edge p2) . (Edge p1) = Edge (p1 >~> p2)

instance (Monad m) => Arrow (Edge m r) where
    arr f = Edge (push />/ respond . f)
    first (Edge p) = Edge $ \(b, d) ->
        evalStateP d $ (up \>\ unsafeHoist lift . p />/ dn) b
      where
        up () = do
            (b, d) <- request ()
            lift $ put d
            return b
        dn c = do
            d <- lift get
            respond (c, d)

instance (Monad m) => ArrowChoice (Edge m r) where
    left (Edge k) = Edge (bef >=> (up \>\ (k />/ dn)))
      where
          bef x = case x of
              Left  b -> return b
              Right d -> do
                  _ <- respond (Right d)
                  x2 <- request ()
                  bef x2
          up () = do
              x <- request ()
              bef x
          dn c = respond (Left c)

runEdge :: (Monad m) => Edge m r a b -> Pipe a b m r
runEdge e = await >>= unEdge e

【问题讨论】:

  • 这是否满足arr (f &gt;&gt;&gt; g) = arr f &gt;&gt;&gt; arr g?我怀疑它没有,但不确定
  • 这是由类别公理引起的,不是吗?
  • This message by Gabriel Gonzalez 对您引用的基于推送的管道实例提供了一些额外的评论。

标签: haskell arrows conduit haskell-pipes


【解决方案1】:

考虑这个管道:yield '*' :: Pipe x Char IO ()。我们可以将它包装在像newtype PipeArrow a b = PipeArrow { getPipeArrow :: Pipe a b IO () } 这样的新型适配器中,并尝试在那里定义Arrow 实例。

购买如何编写适用于yield '*'first :: PipeArrow b c -&gt; PipeArrow (b, d) (c, d)?管道从不等待来自上游的值。我们必须凭空产生一个d,以配合'*'

管道满足箭头(以及ArrowChoice)的大部分法律,但first 不能以合法的方式实施。

您发布的代码没有为Pipe 定义Arrow 实例,而是为从上游获取值并返回Pipe 的函数定义。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-03-25
  • 1970-01-01
  • 1970-01-01
  • 2014-11-07
  • 2010-10-20
  • 1970-01-01
  • 2016-06-23
  • 1970-01-01
相关资源
最近更新 更多