mb14
mb14

Reputation: 22596

How to stop a endBy in Parsec

I'm trying to write a csv-like parser using Parsec. So far so good. The parser decode the header and process everything fine. Now, I'm trying to skip some comments at the beginning of the file. The comment starts with # (or empty line). If I do that, the endBy loop doesn't when the header start but instead fails.

Here is my code:

csvParser = do
   -- skipping comment bit
   P.endBy ((P.char '#' >> P.many (P.noneOf "\n"))
            <|> P.many P.space
           ) eol

   -- real parsing starting
   header <- parseHeader
   eol
   case header of
       ["style", "number", "quantity", "length", "width", "height"] -> parsePL
       otherwise -> error $ "Can't decore following header:" ++ (show header)


   where parseHeader = P.sepBy cell sep
         sep = P.char ','
         eol = P.char '\n'
         cell = P.many (P.noneOf ",\n")
         cellp = do x <- cell ; sep; return x
         today = "2015/01/15" :: Date

         readR :: String -> Rational
         readR x = toRational x' where
                   x' = read x :: Float
         parsePL = P.endBy (do
               style <- cellp
               numberOfBox <- read <$> cellp
               numberPerBox <- cellp
               length <- readR <$> cellp
               width <-  readR <$> cellp
               height <- readR <$> cell

               return (style, numberOfBox, length, width, height, "", 0, "",  today)
               ) eol

Upvotes: 1

Views: 323

Answers (1)

mb14
mb14

Reputation: 22596

I found the problem: space includes line-feed, '\n'.

Upvotes: 2

Related Questions