Re: [Pyparsing] Recursive grammar
Brought to you by:
ptmcg
From: Ralph C. <ra...@in...> - 2007-11-09 11:57:04
|
Hi Thomas, > from pyparsing import * > number = Word(nums) > aexp = Forward() > aexp = Or ([ > number, > number + '+' + aexp , > ]) > > Running the code yields: > > aexp.parseString("3+4") => (['3'], {}) Examine aexp shows >>> aexp {W:(0123...) ^ {{W:(0123...) "+"} Forward:None}} which indicates to me that the Forward hasn't been set to anything. That's because Forwards have to be assigned with `<<' rather than `='. You're forgetting about the Forward created with the initial assignment to aexp by altering aexp to be an Or. I can't find the documentation online, but have a look for something like /usr/share/doc/python2.4-pyparsing/htmldoc/index.html on your machine and see Forward: Forward declaration of an expression to be defined later - used for recursive grammars, such as algebraic infix notation. When the expression is known, it is assigned to the Forward variable using the '<<' operator. When I try: >>> aexp = Forward() >>> aexp << Or ([ ... number, ... number + '+' + aexp , ... ]) Forward:{W:(0123...) ^ {{W:(0123...) "+"} ...}} Which looks a bit better. >>> aexp.parseString("3+4") (['3', '+', '4'], {}) Cheers, Ralph. |