您可以Pipe a b m r
通过参数将 a 连接到副作用,该m
参数会换出Monad
管道正在运行的位置。您可以通过将管道的下游端连接到将链接粘贴在队列中的另一个管道并将管道的上游端连接到从队列中读取链接的管道来使用它来重新排队链接。
我们的目标是写
import Pipes
loopLeft :: Monad m => Pipe (Either l a) (Either l b) m r -> Pipe a b m r
我们将采用一个管道,其下游输出 ,Either l b
要么是Left l
发送回上游的 a ,要么是发送Right b
给下游的 a ,然后将l
s 发送回上游输入Either l a
,该输入要么是排队的,Left l
要么是Right a
来自上游的。我们将Left l
s 连接在一起,形成一个管道,它只看到a
来自上游的 s 并且只产生流向b
下游的 s。
在下游端,我们将l
s 从推入Left l
堆栈。我们yield
来自下游r
。Right r
import Control.Monad
import Control.Monad.Trans.State
pushLeft :: Monad m => Pipe (Either l a) a (StateT [l] m) r
pushLeft = forever $ do
o <- await
case o of
Right a -> yield a
Left l -> do
stack <- lift get
lift $ put (l : stack)
在上游端,我们将在堆栈顶部查找yield
. 如果没有,我们await
将从上游获取一个值yield
。
popLeft :: Monad m => Pipe a (Either l a) (StateT [l] m) r
popLeft = forever $ do
stack <- lift get
case stack of
[] -> await >>= yield . Right
(x : xs) -> do
lift $ put xs
yield (Left x)
现在我们可以写了loopLeft
。我们将上游和下游管道与管道组合一起组成popLeft >-> hoist lift p >-> pushLeft
。将hoist lift
aPipe a b m r
变为 a Pipe a b (t m) r
。将distribute
aPipe a b (t m) r
变为 a t (Pipe a b m) r
。回到 a我们从一个空的 stack 开始Pipe a b m r
运行整个计算。其中和的组合有一个好听的名字。StateT
[]
Pipes.Lift
evalStateP
evalStateT
distribute
import Pipes.Lift
loopLeft :: Monad m => Pipe (Either l a) (Either l b) m r -> Pipe a b m r
loopLeft p = flip evalStateT [] . distribute $ popLeft >-> hoist lift p >-> pushLeft