Frage

I am creating a parse tree that will contain expressions similar to

3 - 4 * 8

or

8 * -5

or

-(10 * 1)

I need a way to distinguish between the unary and binary minus. The way my grammar is going now the binary minus is reached first, but I am thinking of changing that and adding a flag variable that holds the last variable.

Ex: if it is 5 - 6

The flag is holding 5 and if it sees minus and the flag is a number the skip unary and go to binary.

However I am not sure exactly how to implement this in C++

Any help would be greatly appreciated.

Thanks

War es hilfreich?

Lösung

The easiest way to implement a parser is by the method of Recursive Descent. Make sure to give binary minus a higher priority than unary minus, like in the referenced site:

 E -->  | E "+" E
        | E "-" E
        | "-" E
        | E "*" E
        | E "/" E
        | E "^" E
        | "(" E ")"
        | v
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top