Freewind
Freewind

Reputation: 198388

Better solution for "Doing something when a parse fails"?

I can't to do something when a parser fails, in petitparser.

My solution is:

var parser = string("hello").or(
        epsilon().map((_) {
          // do something
        }).seq(failure())
     );

I want to know if there is any better solution?

Upvotes: 1

Views: 124

Answers (1)

Lukas Renggli
Lukas Renggli

Reputation: 8947

Yes, this looks reasonable. The more general form

var parser = string("hello")
  .or(failure("Unable to parse hello"))

is quite common.

However, introducing side-effects in parsers is normally not suggested. That said, you could create a function that encapsulates your pattern as follows:

function handleFailure(Parser parser, Function action, String message) {
  return parser.or(epsilon().map(action).failure(message));
}

Upvotes: 2

Related Questions