如何在Parsec中停止endBy

时间:2015-01-14 18:50:24

标签: haskell parsec

我正在尝试使用Parsec编写类似csv的解析器。到现在为止还挺好。 解析器解码标头并处理一切正常。 现在,我试图在文件开头跳过一些注释。评论以#(或空行)开头。 如果我这样做,endBy循环不会在标题开始时反而失败。

这是我的代码:

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

1 个答案:

答案 0 :(得分:2)

我发现了问题:space包含换行符'\n'