4

在下面的代码中我怎么能

  • 更改stdoutCharConsumer以便在打印输入流中的所有数据后打印换行符

  • 实施mixinmixin'

无需进入 Pipes.Internal?可能吗?我需要类似nextProducers 的功能。

我使用管道 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 ""

UPD:现在,在我阅读了基于拉/推的流之后,我认为即使使用 Pipes.Internal 也是不可能的。这是真的吗?

4

1 回答 1

3

既不Consumers也不Pipes知道上游输入结束。为此,您需要Parsers from pipes-parse

相比Consumers,Parsersa对Producers的了解更直接;当找到输入结束时,它们的draw函数(大致类似于await)返回 a Nothing

import qualified Pipes.Parse as P

stdoutCharParser :: P.Parser Char IO ()
stdoutCharParser = P.draw >>= \ma ->
    case ma of 
        Nothing -> liftIO (putStrLn "\n")
        Just c -> liftIO (putChar c) >> stdoutCharParser

要运行解析器,我们调用evalStateT而不是runEffect

P.evalStateT stdoutCharParser (interleave characters digits) 

至于mixinand mixin',我怀疑它们将无法按预期工作。原因是结果Pipe必须知道上游终止,以便知道何时产生Producer作为参数传递的剩余值。

于 2014-03-15T21:49:34.360 回答