我有一个小的Haskell Pipe,可以打印出它已经运行了多少次:

counterPipe :: Pipe String String IO r
counterPipe = go 0
  where
    go n = do
      await >>= yield
      let n' = succ n
      liftIO $ putStrLn $ "Chunk " ++ show n'
      go n'

一旦处理完最后一块,我希望能够打印出一条消息,并有可能执行其他任务。我该怎么做呢?

最佳答案

我可以通过将counterPipe的输入类型更改为Maybe String并在上游管道完成后注入(inject)额外的Nothing来使其工作:

import Pipes
import Pipes.Core (respond)
import Control.Applicative ((<*))

withEOF :: (Monad m) => Proxy a' a b' b m r -> Proxy a' a b' (Maybe b) m r
withEOF p = for p (respond . Just) <* respond Nothing

counterPipe :: Pipe (Maybe String) String IO Int
counterPipe = go 0
  where
    go n = do
        mx <- await

        case mx of
            Just x -> do
                yield x
                let n' = succ n
                liftIO $ putStrLn $ "Chunk " ++ show n'
                go n'
            Nothing -> do
                return n

finishCounter :: Int -> Pipe a b IO ()
finishCounter n = liftIO $ putStrLn $ unwords ["Finished after", show n, "chunks"]

驱动程序示例:
import qualified Pipes.Prelude as P
main = runEffect $ withEOF P.stdinLn >-> (counterPipe >>= finishCounter) >-> P.stdoutLn

我认为这种模式应该可以抽象为
whileJust :: (Monad m) => Proxy a' a b' b m r -> Proxy a' (Maybe a) b' b m (Maybe r)

所以你可以写
withEOF P.stdinLn >-> (whileJust counterPipe >>= maybe (return ()) finishCounter) >-> P.stdoutLn

无需更改原始的counterPipe定义;
但是我以前从未使用过Pipes(上面的解决方案是通过查看类型并播放type-domino来解决的),因此我还没有设法编写whileJust(签名可能太通用了,以至于我无法弄清楚出去)。

10-08 02:39