Search code examples
haskellparsecparser-combinators

How to trigger error during manyAccum parser


I would like to write a Parsec parser that would parse a sequence of numbers, returning a sorted list, but failing on encountering a duplicate number (the error should point to the position of the duplicate). For the sorted part I can simply use:

manySorted = manyAccum insert

But how can I trigger a Parsec error if the number is already on the list. It doesn't seem like manyAccum allows that and I couldn't figure out how to make my own clone of manyAccum that would (implementation uses unParser which doesn't seem to be exposed outside of Parsec library).


Solution

  • You could try to obtain the current parser's position by

    sourcePos :: Monad m => ParsecT s u m SourcePos
    sourcePos = statePos `liftM` getParserState
    

    Then accumulate the positions together with parsed values so that you can report the position of the original.