I want to write a Parser that produces some data structure and validates its consistency by running a predicate on it. In case the predicate returns false the parser should return a custom Error object (as opposed to a Failure, since this can be achieved by ^?).
I am looking for some operator on parser that can achieve that.
For example, let’s say that I want to parse a list of integers and check that they are distinct. I would like to have something like this:
import util.parsing.combinator.RegexParsers
object MyParser extends RegexParsers {
val number: Parser[Int] = """\d+""".r ^^ {_.toInt }
val list = repsep(number, ",") ^!(checkDistinct, "numbers have to be unique")
def checkDistinct(numbers: List[Int]) = (numbers.length == numbers.distinct.length)
}
The ^! in the code above is what I am looking for. How can I validate a parser output and return a useful error message if it does not validate?
^?accepts an error message generator,commitconverts aFailureto anError: