Skip to content

Parsec - how to implement recursive grammar? #1004

Answered by louthy
AlesSturala asked this question in Q&A
Discussion options

You must be logged in to vote

So, here's a few tips:

1. Declare ex before-hand as null

   Parser<YourExpr> ex = null;

2. The first line of the LINQ expression can't refer to ex

    ex = from ... in THIS_WILL_BE_EVALUATED_IMMEDIATELY
         from ... in THIS_WILL_BE_EVALUATED_LAZILY
         select ...;

Because the right-hand-side of the first in is evaluated immediately, ex will be null. And so, your between parser won't be particularly useful.

You can fix this (in general), by using lazyp(() => ex), which will evaluate ex later, when it's got a value.

    ex = from ws in choice(between(lb, rb, lazyp(() => ex)), number)
         select ws;

Or, move the recursion to the second line of the parser, this can be done by c…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by AlesSturala
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants