为什么导管和管道不能具有Arrow实例?

use*_*201 5 haskell arrows conduit haskell-pipes

在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
Run Code Online (Sandbox Code Playgroud)

dan*_*iaz 5

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

购买如何编写一个first :: PipeArrow b c -> PipeArrow (b, d) (c, d)可以运行的程序yield '*'?管道从不等待来自上游的值。我们就得d凭空产生一个,来陪伴'*'

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

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

  • 这个很好的答案的[姊妹篇](https://www.paolocapriotti.com/blog/2012/02/04/monoidal-instances-for-pipes/)。 (2认同)