1

I have the following piece of code for solving a simple arithmetic expression. I want to modify to run it for expressions with constant identifiers. For example, the following code will work for (2 *3.14 * 5), but will not work for (2*pi* 5) where pi =3.14. One way to handle is to first parse the string and do a find and replace before passing the string to boost spirit. Can this be done inside the boost code itself. Any suggestions are welcome. Thanks.

#include <boost/config/warning_disable.hpp>
#include "boost/spirit/include/qi.hpp"
#include "boost/spirit/include/phoenix_core.hpp"
#include "boost/spirit/include/phoenix_operator.hpp"
#include "boost/spirit/include/phoenix_stl.hpp"
#include <stdlib.h>
#include <stdio.h>

#include <iostream>
#include <string>

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;

using qi::phrase_parse;
using qi::_1;
using ascii::space;
using phoenix::push_back;
using qi::double_;


  template <typename Iterator>
    struct calculator : qi::grammar<Iterator, double(), ascii::space_type>
  {
    calculator() : calculator::base_type(expression)
    {


      using qi::_val;
      using qi::lexeme_d;
      using qi::alpha_p;
      using qi::alnum_p;
      using qi::_1;

      expression =
        term                            [_val = _1]
        >> *(   ('+' >> term            [_val += _1])
            |   ('-' >> term            [_val -= _1])
            )
        ;

      term =
        factor                          [_val = _1]
        >> *(   ('*' >> factor          [_val *= _1])
            |   ('/' >> factor          [_val /= _1])
            )
        ;

      factor =
        double_                           [_val = _1]
        |   '(' >> expression           [_val = _1] >> ')'
        |   ('-' >> factor              [_val = -_1])
        |   ('+' >> factor              [_val = _1])
        ;
    }

    qi::rule<Iterator, double(), ascii::space_type> expression, term, factor;
  };
Claudio
  • 10,614
  • 4
  • 31
  • 71
  • 1
    Before resorting to a preprocessor, see if the [relevant Boost.Spirit example](https://raw.githubusercontent.com/boostorg/spirit/master/classic/example/fundamental/more_calculators/calc_with_variables.cpp) solves the problem for you. – Sean Cline Jan 18 '16 at 13:34
  • The code shown is half-antiquated. The sample are indeed a good place to start. Then, sample the Qi answers on [SO]. Here's one relevant one: https://stackoverflow.com/a/32501979/85371 – sehe Jan 18 '16 at 14:02

0 Answers0