在下面的代码中,我该如何:
更改
stdoutCharConsumer
,以便在打印完输入流中的所有数据后打印换行符实现
mixin
和mixin'
而不需要进入Pipes.Internal?这是可能的吗?我需要类似于生产者的next
函数。
我使用的是Pipes 4.1.0版本。
#!/usr/bin/env runhaskell
{-# OPTIONS_GHC -Wall #-}
import Pipes
digits, characters :: Monad m => Producer Char m ()
digits = each "0123456789"
characters = each "abcdefghijklmnopqrstuvwxyz"
interleave :: Monad m => Producer a m () -> Producer a m () -> Producer a m ()
interleave a b = do
n <- lift $ next a
case n of
Left () -> b
Right (x, a') -> do
yield x
interleave b a'
stdoutCharConsumer :: Consumer Char IO ()
stdoutCharConsumer = await >>= liftIO . putChar >> stdoutCharConsumer
-- first element of the mixin should go first
mixin :: Monad m => Producer b m () -> Pipe a b m ()
mixin = undefined
-- first element of the pipe should go first
mixin' :: Monad m => Producer b m () -> Pipe a b m ()
mixin' = undefined
main :: IO ()
main = do
-- this prints "a0b1c2d3e4f5g6h7i8j9klmnopqrstuvwxyz"
runEffect $ interleave characters digits >-> stdoutCharConsumer
putStrLn ""
-- this prints "0a1b2c3d4e5f6g7h8i9jklmnopqrstuvwxyz"
runEffect $ interleave digits characters >-> stdoutCharConsumer
putStrLn ""
-- should print "0a1b2c3d4e5f6g7h8i9jklmnopqrstuvwxyz"
runEffect $ characters >-> mixin digits >-> stdoutCharConsumer
putStrLn ""
-- should print "a1b2c3d4e5f6g7h8i9jklmnopqrstuvwxyz"
runEffect $ digits >-> mixin characters >-> stdoutCharConsumer
putStrLn ""
-- should print "a1b2c3d4e5f6g7h8i9jklmnopqrstuvwxyz"
runEffect $ characters >-> mixin' digits >-> stdoutCharConsumer
putStrLn ""
-- should print "0a1b2c3d4e5f6g7h8i9jklmnopqrstuvwxyz"
runEffect $ digits >-> mixin' characters >-> stdoutCharConsumer
putStrLn ""
更新:现在我已经了解了基于推/拉流的知识,我认为即使使用 Pipes.Internal 也不可能实现。这是真的吗?
interleave
的工作原理吗?请注意,当管道p
完成时,next p
会返回Left result
。 - pashnext
有更一般的类型。如果你深入研究Pipes.Internal
,可以查看MonadPlus
实例,寻找灵感。也许您可以调整mplus
实现背后的思路,以获得更通用的Proxy
值类似于interleave
的功能。 - pash