你绝对不想用pipes
这个。但是,您可以做的是定义一个受限类型来执行此操作,在该受限类型中执行所有连接和逻辑,然后在完成后将其提升为 a Pipe
。
您想要的类型是这样的,类似于netwire
Wire
:
{-# LANGUAGE DeriveFunctor #-}
import Control.Monad.Trans.Free -- from the 'free' package
data WireF a b x = Pass (a -> (b, x)) deriving (Functor)
type Wire a b = FreeT (WireF a b)
这自动是一个 monad 和一个 monad 转换器,因为它是根据FreeT
. 然后就可以实现这个方便的操作了:
pass :: (Monad m) => (a -> b) -> Wire a b m ()
pass f = liftF $ Pass (\a -> (f a, ()))
...并使用单子语法组装自定义电线:
example :: Wire Int Int IO ()
example = do
pass (+ 1)
lift $ putStrLn "Hi!"
pass (* 2)
然后,当您完成使用此受限Wire
类型连接事物时,您可以将其提升为Pipe
:
promote :: (Monad m) => Wire a b m r -> Pipe a b m r
promote w = do
x <- lift $ runFreeT w
case x of
Pure r -> return r
Free (Pass f) -> do
a <- await
let (b, w') = f a
yield b
promote w'
请注意,您可以定义标识以及线和线组合:
idWire :: (Monad m) => Wire a a m r
idWire = forever $ pass id
(>+>) :: (Monad m) => Wire a b m r -> Wire b c m r -> Wire a c m r
w1 >+> w2 = FreeT $ do
x <- runFreeT w2
case x of
Pure r -> return (Pure r)
Free (Pass f2) -> do
y <- runFreeT w1
case y of
Pure r -> return (Pure r)
Free (Pass f1) -> return $ Free $ Pass $ \a ->
let (b, w1') = f1 a
(c, w2') = f2 b
in (c, w1' >+> w2')
我很确定这些形成Category
:
idWire >+> w = w
w >+> idWire = w
(w1 >+> w2) >+> w3 = w1 >+> (w2 >+> w3)
另外,我很确定它promote
遵守以下函子定律:
promote idWire = cat
promote (w1 >+> w2) = promote w1 >-> promote w2