Search code examples
c++grammarfactorial

Adding higher-level operator to grammar


I am working through Stroustrups Programming Principles and Practice using c++. There is this grammar that he uses in building a calculator through the first few chapters of the book. One of the exercises is to add a factorial operator to the calculator. He gives a hint

Begin by modifying the grammar to account for a higher-level operator

What is a higher-level operator? (unfortunately he hasn't explained it up to that chapter in the book and I don't know if its even been explained in other chapters)

The grammar he is asking to be modified is this:

Expression:
    Term
    Expression "+" Term
    Expression "-" Term
Term:
    Primary
    Term "*" Primary
    Term "/" Primary
    Term "%" Primary
Primary:
    Number
    "(" Expression ")"
Number:
    floating-point-literal

I have grappled with this for a whole day now and I'm getting nowhere. Will be glad for some explanation.


Solution

  • A higher-level operator is an operator which has a greater precedence than others.

    This can be added to your grammar the same way the multiplication, divisions, and modulo differ from the addition and soustraction.

    In other words, your parser should first attempt to parse factorial syntax, then multiplication, then addition