Skip to content

Instantly share code, notes, and snippets.

@K240-zz
Created February 3, 2012 17:24
Show Gist options
  • Select an option

  • Save K240-zz/1731263 to your computer and use it in GitHub Desktop.

Select an option

Save K240-zz/1731263 to your computer and use it in GitHub Desktop.
Simple Expression using boost::spirit
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include <boost/fusion/tuple.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
using namespace std;
using namespace boost;
using namespace boost::spirit;
struct sin_expr
{
template <typename T>
struct result { typedef T type; };
double operator()(double const& expr) const
{
return double(::sin(expr));
}
};
struct cos_expr
{
template <typename T>
struct result { typedef T type; };
double operator()(double const& expr) const
{
return double(::cos(expr));
}
};
boost::phoenix::function<sin_expr> Sin;
boost::phoenix::function<cos_expr> Cos;
template<typename Iterator>
struct calc : qi::grammar<Iterator, double(), ascii::space_type>
{
qi::rule<Iterator, double(), ascii::space_type> expr, term, fctr;
calc() : calc::base_type(expr)
{
expr = term[_val = _1] >> *( ('+' >> term[_val += _1])
| ('-' >> term[_val -= _1]) );
term = fctr[_val = _1] >> *( ('*' >> fctr[_val *= _1])
| ('/' >> fctr[_val /= _1]) );
fctr = double_[_val = _1]
| '(' >> expr[_val = _1] >> ')'
| ( '-' >> fctr[_val = -_1])
| ( '+' >> fctr[_val = _1])
| lit("sin") >> '(' >> expr[_val = Sin(_1)] >> ')'
| lit("cos") >> '(' >> expr[_val = Cos(_1)] >> ')'
;
}
};
double do_expression(string value)
{
calc<string::iterator> c;
double result = std::numeric_limits<double>::signaling_NaN();
string::iterator it = value.begin();
qi::phrase_parse(it, value.end(), c, ascii::space, result);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment