6

我正在尝试了解管道 4.0,并想转换一些管道代码。假设我有一个Ints 流,我想跳过前五个,然后得到以下 5 个的总和。使用普通列表,这将是:

sum . take 5 . drop 5

在管道中,这将是:

drop 5
isolate 5 =$ fold (+) 0

或者作为一个完整的程序:

import Data.Conduit
import Data.Conduit.List (drop, isolate, fold)
import Prelude hiding (drop)

main :: IO ()
main = do
    res <- mapM_ yield [1..20] $$ do
        drop 5
        isolate 5 =$ fold (+) 0
    print res

但是,我不太确定如何使用管道执行此操作。

4

2 回答 2

5

我以前没有使用过 Pipes,但是在阅读完教程后,我发现它非常简单:

import Pipes
import qualified Pipes.Prelude as P

nums :: Producer Int IO ()
nums = each [1..20]

process :: Producer Int IO ()
process = nums >-> (P.drop 5) >-> (P.take 5)

result :: IO Int
result = P.fold (+) 0 id process

main = result >>= print

更新:

由于示例中没有“有效”的处理,我们甚至可以使用Identitymonad 作为管道的基本 monad:

import Pipes
import qualified Pipes.Prelude as P
import Control.Monad.Identity

nums :: Producer Int Identity ()
nums = each [1..20]

process :: Producer Int Identity ()
process = nums >-> (P.drop 5) >-> (P.take 5)

result :: Identity Int
result = P.fold (+) 0 id process

main = print $ runIdentity result

更新 1

下面是我想出的解决方案(对于要点链接评论),但我觉得它可以变得更优雅

fun :: Pipe Int (Int, Int) Identity ()
fun = do
  replicateM_ 5 await
  a <- replicateM 5 await
  replicateM_ 5 await
  b <- replicateM 5 await
  yield (sum a, sum b)

main = f $ runIdentity $ P.head $ nums >-> fun where
  f (Just (a,b)) = print (a,b)
  f Nothing = print "Not enough data"
于 2013-09-24T09:02:31.860 回答
4

To answer your comment, this still works in the general case. I also posted the same answer on reddit where you also asked a similar question there, but I'm duplicating the answer here:

import Pipes
import Pipes.Parse
import qualified Pipes.Prelude as P

main :: IO ()
main = do
    res <- (`evalStateT` (each [1..20])) $ do
        runEffect $ for (input >-> P.take 5) discard
        P.sum (input >-> P.take 5)
    print res

This will generalize to the more complicated cases that you had in mind.

于 2013-09-24T22:18:09.123 回答