Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help on making the recursive parser using pyparsing

I am trying the python pyparsing for parsing. I got stuck up while making the recursive parser.

Let me explain the problem

I want to make the Cartesian product of the elements. The syntax is

cross({elements },{element})

I put in more specific way

cross({a},{c1}) or cross({a,b},{c1}) or cross({a,b,c,d},{c1}) or 

So the general form is first group will have n elements (a,b,c,d). The second group will have one element that so the final output will be Cartesian Product.

The syntax is to be made recursive because it can go to n level like

cross(cross({a,b},{c1}),{c2})

This means cross a,b with c1. Lets say outcome us y. We again cross y it with c2

This can be till n level cross(cross(cross(cross......

What i want is to have object to be initialized using setparseAction

So i will have 2 class

class object1(object):
     This will be used by a,b,c,d 

class object2(object):
       This will hold cross elements

I need help on this i am not able to make the recursive parser.


1 Answers

You should look at definitions of other languages to see how this is usually handled.

For example, look at how multiplication is defined.

It isn't

{expression} * {expression}

Because the recursion is hard to deal with, and there's no implied left-to-right ordering. What you see more often are things like

{term} + {factor}
{factor} * {unary-expression}

Which puts priorities and a left-to-right ordering around the operators.

Look at something like http://www.cs.man.ac.uk/~pjj/bnf/c_syntax.bnf for examples of how things like this are commonly structured.

like image 166
S.Lott Avatar answered Jan 29 '26 11:01

S.Lott