Re: [Pyparsing] Success (though minor) was: A newbie w/nested structures
Brought to you by:
ptmcg
From: Ralph C. <ra...@in...> - 2007-09-10 10:04:20
|
Hi Tim, > I must figure out today how to properly exploit Forward(). :-> I haven't seen anyone try and explain this, so I'll have a go. I read up on PyParsing ages ago, but I think this is right... I assume you're happy with normal recursion, e.g. def add(a, b): 'Add two non-negative numbers.' if b == 0: return a return add(a + 1, b - 1) Notice how we can write a call to add() inside add() despite the definition of add() not being finished yet. That's something Python allows. Now consider a data structure where each node has a `next' pointer to another node of the same type. If we want a circular definition where we've just a single node whose `next' point points to itself, we can't do >>> a = { 'next': a } Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'a' is not defined >>> This is because `a' only exists once the definition of `a' is finished; notice how this is different to add() above. A solution is a placeholder. I'll use None. >>> a = { 'next': None } >>> a['next'] = a >>> import pprint >>> pprint.pprint(a) {'next': <Recursion on dict with id=-1210075780>} >>> PyParsing has the same issue when trying to set up the data structures representing the grammar. Instead of using `None' it has Forward(). The idea is the same; it's a placeholder that is later replaced by something else. Something that exists later that didn't exist at the time the Forward() was required. Once this concept clicks, you'll see it's really quite simple. :-) Cheers, Ralph. |