2017-02-23 43 views
4

在reddit上有一个存档的线程,它说本质上管道/管道不能是箭头b/c箭头需要同步。此处链接的线程为https://www.reddit.com/r/haskell/comments/rq1q5/conduitssinks_and_refactoring_arrows/为什么Conduit和Pipe没有Arrow实例?

我无法看到“同步”在哪里,因为这不是箭头定义的一部分。另外,我偶然发现了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 
+0

这是否满足'arr(f >>> g)= arr f >>> arr g'?我怀疑它不会但不确定 – hao

+0

这是由类别公理引起的,不是吗? – user2812201

+0

[Gabriel Gonzalez的此消息](https://groups.google.com/d/msg/haskell-pipes/H6YdVhyNksk/xr4NAPHzT2UJ)对您引用的基于推送的管道的实例提供了一些额外的注释。 – duplode

回答

4

考虑这个管道: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不能以合法的方式实施。

您发布的代码没有为Pipe定义Arrow intance,但是对于从上游获取值并返回Pipe的函数。

+2

A [companion piece](https://www.paolocapriotti.com/blog/2012/02/04/monoidal-instances-for-pipes/)这个很好的答案。 – duplode

相关问题