First line pass in attopar pipes

My types are:

data Test = Test {
 a :: Int,
 b :: Int
} deriving (Show)

My parser:

testParser :: Parser Test
testParser = do
  a <- decimal
  tab
  b <- decimal
  return $ Test a b

tab = char '\t'

Now, to skip the first line, I am doing something like this:

import qualified System.IO as IO    

parser :: Parser Test
parser = manyTill anyChar endOfLine *> testParser

main = IO.withFile testFile IO.ReadMode $ \testHandle -> runEffect $
         for (parsed (parser <* endOfLine) (fromHandle testHandle)) (lift . print)

But the above function parsermakes every alternate link skipped (which is obvious). As soon as you skip the first line so that it works with the Pipes ecosystem ( Producershould result in a single value Test). This is one obvious solution that I do not want (the code below will work if I change testParser to read new lines) because it returns an integer [Test]instead of a single value:

tests :: Parser [Test]
tests = manyTill anyChar endOfLine *>
        many1 testParser

Any ideas to solve this problem?

+4
source share
2 answers

:

import Lens.Family (over)
import Pipes.Group (drops)
import Pipes.ByteString (lines)
import Prelude hiding (lines)

dropLine :: Monad m => Producer ByteString m r -> Producer ByteString m r
dropLine = over lines (drops 1)

dropLine Producer, Producer, :

main = IO.withFile testFile IO.ReadMode $ \testHandle -> runEffect $
    let p = dropLine (fromHandle testHandle)
    for (parsed (parser <* endOfLine) p) (lift . print)
+5

Test, Either () Test :

parserEither :: Parser (Either () Test)
parserEither = Right <$> testParser <* endOfLine 
           <|> Left <$> (manyTill anyChar endOfLine *> pure ())

, Pipes.Prelude, (, , ):

producer p = parsed parserEither p 
         >-> P.drop 1 
         >-> P.filter (either (const False) (const True))
         >-> P.map    (\(Right x) -> x)

main = IO.withFile testFile IO.ReadMode $ \testHandle -> runEffect $
         for (producer (fromHandle testHandle)) (lift . print)
+5

Source: https://habr.com/ru/post/1547884/


All Articles