3 ms·
Recently I wrote a parser generator, which would take a rule structure and return a function that does the parsing. Lambdas were very useful here, and I do not
by ThePhysicist 10y ago
Recently I wrote a parser generator, which would take a rule structure and return a function that does the parsing. Lambdas were very useful here, and I do not know how I would've implemented this without them, at least in an efficient manner, because they let me do something like this:
Parser ParserGenerator::compileLiteral(Rule& rule){
const string literal = rule.value;
Parser parser = [literal] (shared_ptr<State> state){
//parse the literal...
state.Advance(literal.size())
return state;
}
return parser
}
Solving this without lambdas would require a different encapsulation mechanism for the rule data, such as a class, which (IMHO) would make the code less idiomatic.
So lambdas are actually very useful!
- nly 10y agoWell, an alternative approach might to not to couple parsing and state manipulation :) PEGTL does this. Approximately, you have a template parameter MyAction<> on the Parser<> template which in turn calls "MyAction<Rule>::apply (state)" when parsing of each rule is complete. It's a fantastic library. I highly recommend giving it a whirl. [0] https://github.com/ColinH/PEGTL/blob/master/doc/Actions-and-States.md https://github.com/ColinH/PEGTL/blob/master/doc/Actions-and-...