com-lihaoyi / fastparse

Writing Fast Parsers Fast in Scala
https://com-lihaoyi.github.io/fastparse
MIT License
1.09k stars 164 forks source link

Support for predicate tests to indicate Success or Failure for parsers of T #23

Closed russwyte closed 9 years ago

russwyte commented 9 years ago

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)

lihaoyi commented 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.

russwyte commented 9 years ago

That is precisely what I would suggest. :)

lihaoyi commented 9 years ago

Feel free to send a PR!

russwyte commented 9 years ago

I created PR #24 to add filter transformer.