Haskell 管道——让管道消耗它产生的(本身)

Haskell Pipes -- Having a pipe consume what it yields (itself)

我正在尝试使用 Pipes 编写一个网络爬虫,我已经来到了跟踪抓取链接的部分。我有一个 process 函数,可以下载 url、查找链接并生成它们。

process :: Pipe Item Item (StateT CState IO) ()
 ....
    for (each links) yield
 ....

现在我想知道如何递归地跟踪这些链接,使 StateT 贯穿始终。我意识到可能会做一些更惯用的事情,然后将单个管道用于大部分刮板(尤其是当我开始添加更多功能时),我愿意接受建议。无论如何,当我考虑带共享状态的多线程时,我可能不得不重新考虑设计。

我会这样做:

import Pipes

type Url = String

getLinks :: Url -> IO [Url]
getLinks = undefined

crawl :: MonadIO m => Pipe Url Url m a
crawl = loop []
  where
    loop [] = do url <- await; loop [url]
    loop (url:urls) = do
      yield url
      urls' <- liftIO $ getLinks url
      loop (urls ++ urls')

根据 url'urls 的结合方式,您可以实现 DFS 或 BFS。

您可以通过 m 参数将 Pipe a b m r 连接到副作用,该参数会换出管道正在运行的 Monad。您可以通过将管道的下游端连接到另一个将链接放入队列中的管道并将管道的上游端连接到从队列中读取链接的管道来使用它来重新排队链接。

我们的目标是写

import Pipes

loopLeft :: Monad m => Pipe (Either l a) (Either l b) m r -> Pipe a b m r

我们将采用一个管道,其下游输出 Either l b 是一个 Left l 发送回上游或 Right b 发送回下游,然后发送 ls 回到上游输入 Either l a,它是排队的 Left l 或来自上游的 Right a。我们将 Left ls 连接在一起,形成一个管道,该管道只能看到来自上游的 as,并且只会产生 bs 流向下游。

在下游端,我们将 Left l 中的 l 推入堆栈。我们 yield 来自 Right r 下游的 r

import Control.Monad
import Control.Monad.Trans.State

pushLeft :: Monad m => Pipe (Either l a) a (StateT [l] m) r
pushLeft = forever $ do
    o <- await
    case o of
        Right a -> yield a
        Left l -> do
            stack <- lift get
            lift $ put (l : stack)

在上游端,我们将在堆栈顶部寻找一些东西到 yield。如果没有,我们将 await 从上游获取一个值并 yield 它。

popLeft :: Monad m => Pipe a (Either l a) (StateT [l] m) r
popLeft = forever $ do
    stack <- lift get
    case stack of
        [] -> await >>= yield . Right
        (x : xs) -> do
            lift $ put xs
            yield (Left x)

现在我们可以写 loopLeft。我们将上游和下游管道与管道组合 popLeft >-> hoist lift p >-> pushLeft 组合在一起。 hoist liftPipe a b m r 变成 Pipe a b (t m) revalStateTdistribute.

组合的 distribute turns a Pipe a b (t m) r into a t (Pipe a b m) r. To get back to a Pipe a b m r we run the whole StateT computation starting with an empty stack []. In Pipes.Lift there's a nice name evalStateP
import Pipes.Lift

loopLeft :: Monad m => Pipe (Either l a) (Either l b) m r -> Pipe a b m r
loopLeft p = flip evalStateT [] . distribute $ popLeft >-> hoist lift p >-> pushLeft