Re: [Pyparsing] Recursive grammar
Brought to you by:
ptmcg
From: Ralph C. <ra...@in...> - 2007-11-09 18:08:00
|
Hi Thomas, > The reason I tried to build a minimal example in the first place was > that I had double recursion in my initial version, something like > > aexp << Or([..., > aexp + '+' + aexp, > ...]) > > which results in infinite recursion. I felt this might be the right > way to do it, but maybe I'm wrong. Is this generally possible in > pyparsing? I doubt it is. If you look at a grammar for a language you tend to find arithmetical expressions defined: expr := term (addop term)* term := factor (mulop factor)* factor := floatnum | '(' expr ')' addop := '+' | '-' mulop := '*' | '/' This makes the grammar, and the parse tree, represent the precedence of operators. Note the parenthesis are handled with the recursive definition where `expr' was a Forward() initially. Using ZeroOrMore() it's quite easy to turn the above into Python. Maybe fourFn.py will make a little more sense now > > And I would also suggest that you try to use the MatchFirst > > construct instead of Or, especially with recursive expressions: > > > > aexp << ( number + '+' + aexp | number ) > > I presume this will gain me some run-time efficiency. Yes. Or() tries all of them and then returns the longest. MatchFirst() can give up trying after the first one that matches. Cheers, Ralph. |