3

我试图了解管道解析 3.0 如何处理除spanand之外的情况splitAt,但无法完全弄清楚如何让事情正常进行。基本思想是我有一个同构,我想映射所有输入值以从 type 转换A为 type B。然后,我希望将所有剩菜从转换BA. 我将如何做到这一点pipes-parse

为了比较,代码如下所示conduit

import           Control.Applicative ((<$>), (<*>))
import           Data.Conduit        (yield, ($$), (=$=))
import           Data.Conduit.Extra  (fuseLeftovers)
import qualified Data.Conduit.List   as CL

newtype A = A Int
    deriving Show
newtype B = B Int
    deriving Show

atob (A i) = (B i)
btoa (B i) = (A i)

main :: IO ()
main = do
    let src = mapM_ (yield . A) [1..10]
    res <- src $$ (,,,)
        <$> fuseLeftovers (map btoa) (CL.map atob) CL.peek
        <*> CL.take 3
        <*> (CL.map atob =$= CL.take 3)
        <*> CL.consume
    print res

编辑:为了澄清,这是我上面代码的输出:

(Just (B 1),[A 1,A 2,A 3],[B 4,B 5,B 6],[A 7,A 8,A 9,A 10])

请注意,原始流的类型为A. 我们正在转换B并查看第一个元素,然后将接下来的 3 个元素作为 type A,然后将以下三个作为B,最后将其余的作为A

4

1 回答 1

3

我通过引入一个辅助镜头组合器来做到这一点,piso :: Iso' a b -> Iso' (Producer a m r) (Producer b m r)

import           Control.Applicative
import           Control.Lens               (view, from, zoom, iso, Iso')
import           Control.Monad.State.Strict (evalState)
import           Pipes
import           Pipes.Core                 as Pc
import qualified Pipes.Parse                as Pp
import qualified Pipes.Prelude              as P

newtype A = A Int
    deriving Show
newtype B = B Int
    deriving Show

atob (A i) = B i
btoa (B i) = A i

ab :: Iso' A B
ab = iso atob btoa

piso :: Monad m => Iso' a b -> Iso' (Producer a m r) (Producer b m r)
piso i = iso (P.map (view i) <-<) (>-> P.map (view $ from i))

main :: IO ()
main = do
  let src = P.map atob <-< P.map A <-< each [1..10]
  let parser = (,,) <$> zoom (Pp.splitAt 1) Pp.peek
                    <*> zoom (Pp.splitAt 3 . piso (from ab)) Pp.drawAll
                    <*> Pp.drawAll
  let res = evalState parser src
  print res

这里src是 aProducer B m rparsera Parser B m (Maybe B, [A], [B])。我认为这个问题的核心是,在一些先前的解析操作之后,剩余部分只是在Parser-State范围内发生的事情。Producer因此,您可以zoom像往常一样使用它来修改Producer您喜欢的内容。

请注意,我们可以颠倒镜头的顺序并这样做,zoom (piso (from ab) . Pp.splitAt 3) Pp.drawAll但由于镜头从左到右下降,这意味着我们要Producer在关注接下来的三个元素之前修改整个镜头。在我的主要示例中使用顺序可以减少 和 之间的映射A数量B

view (Pp.splitAt 3 . piso (from ab))
  :: Monad m => Producer B m x -> (Producer A m (Producer B m x))
  -- note that only the outer, first Producer has been mapped over, the protected,
  -- inner producer in the return type is isolated from `piso`'s effect

view (piso (from ab) . Pp.splitAt 3)
  :: Monad m => Producer B m x -> (Producer A m (Producer A m x))
于 2014-02-08T19:21:52.010 回答