Closed russwyte closed 9 years ago
Sounds reasonable. I'd just call it filter
^_^
On Mon, Jun 1, 2015 at 12:36 PM, Russ White notifications@github.com wrote:
If this feature already exists I apologize for missing it.
It would be nice to have a built in construct for parsers with predicates like this: import fastparse. object Parser { def predicatedT(pred: T => Boolean): Parser[T] = P { parser.flatMap(x => if (pred(x)) Pass.map( => x) else Fail) } val pDigits: Parser[Int] = P(CharIn('0' to '9').rep(1).!.map(_.toInt)) val pEven: Parser[Int] = predicated(pDigits)({x => x % 2 == 0}) val pOdd: Parser[Int] = predicated(pDigits)({x => x % 2 != 0}) }
object Run extends App { import Parser._ println(pEven.parse("123")) println(pEven.parse("124")) println(pOdd.parse("123")) println(pOdd.parse("124")) } Run... Failure(predicated:0 / Fail:3 ..."", false) Success(124, 3) Success(123, 3) Failure(predicated:0 / Fail:3 ..."", false)
— Reply to this email directly or view it on GitHub https://github.com/lihaoyi/fastparse/issues/23.
That is precisely what I would suggest. :)
Feel free to send a PR!
I created PR #24 to add filter transformer.
If this feature already exists I apologize for missing it.
It would be nice to have a built in construct for parsers with predicates like this: import fastparse. object Parser { def predicated[T](parser: Parser[T])(pred: T => Boolean): Parser[T] = P { parser.flatMap(x => if (pred(x)) Pass.map( => x) else Fail) } val pDigits: Parser[Int] = P(CharIn('0' to '9').rep(1).!.map(_.toInt)) val pEven: Parser[Int] = predicated(pDigits)({x => x % 2 == 0}) val pOdd: Parser[Int] = predicated(pDigits)({x => x % 2 != 0}) }
object Run extends App { import Parser._ println(pEven.parse("123")) println(pEven.parse("124")) println(pOdd.parse("123")) println(pOdd.parse("124")) } Run... Failure(predicated:0 / Fail:3 ..."", false) Success(124, 3) Success(123, 3) Failure(predicated:0 / Fail:3 ..."", false)