How to properly read to stop words with Parsec?

49 views Asked by At

I can't figure out how to read text with parsec to a stop word, I understand that you can do something like this

paramBlockExpr :: Parser ParamBlock
paramBlockExpr = do
  p <- paramExpr
  txt <- many1 anyChar 
  _ <- string "stop_word"
  return $ ParamBlock p txt

But then parsec will move the carriage and stop_word is no longer readable, I read something about lookAHead, but I do not understand if it is applicable here

P.S

By the way the example will not work either, anyChar will absorb stop_word

2

There are 2 answers

1
Daniel Wagner On

Like this:

absorbToStopWord :: Parser String
absorbToStopWord = try ("" <$ string "stop_word")
               <|> liftA2 (:) anyChar absorbToStopWord
0
student422 On

I took Daniel Wagner's feature (thanks to him for that) and tweaked it a bit, so now it looks like this:

absorbToStopWordNoRead :: String -> Parser String
absorbToStopWordNoRead stopWord = lookAhead ("" <$ string stopWord)
                       <|> liftA2 (:) anyChar (absorbToStopWordNoRead stopWord)