52 OpSearch {
true,
bAdd, 0,
'+', [](
double a,
double b) {
return a +
b; }},
53 OpSearch {
true,
bSub, 0,
'-', [](
double a,
double b) {
return a -
b; }},
54 OpSearch {
true,
bMul, 1,
'*', [](
double a,
double b) {
return a *
b; }},
55 OpSearch {
true,
bDiv, 1,
'/', [](
double a,
double b) {
return a /
b; }},
58 return std::pow(a,
b); }
63 expr.erase(remove_if(expr.begin(), expr.end(), isspace), expr.end());
84 for (
int i = expr.size() - 1;
i >= 0;
i--) {
90 if (par < 0)
return NULL;
91 if (par > 0)
continue;
93 for (
unsigned opt = 0; opt <
ops.size(); opt++) {
94 if (
ops[opt].priority !=
p)
continue;
95 if (
ops[opt].
c == expr[
i]) {
99 l =
parse(expr.substr(0, i));
101 if ((l && r) || (!
ops[opt].binary &&
r)) {
115 if (expr.size() >= 2 && expr[0] ==
'(' && expr[expr.size() - 1] ==
')')
116 return parse(expr.substr(1, expr.size() - 2));
121 double v = strtod(expr.c_str(), &sptr);
122 if (sptr != expr.c_str()) {
132 bool contains_non_alpha =
false;
134 contains_non_alpha = contains_non_alpha or
135 !( (
c >=
'a' &&
c <=
'z') ||
136 (
c >=
'A' &&
c <=
'Z') ||
137 (
c >=
'0' &&
c <=
'9') ||
138 c ==
'$' ||
c ==
'\\' ||
c ==
'.' ||
c ==
'_');
140 if (!contains_non_alpha) {
160 for (
auto & opt :
ops)
162 return opt.fn(
eval(n->
l, fn),
eval(n->
r, fn) );
164 panic(
"Invalid node!\n");
171 ret += prefix +
"|-- " + n->
toStr() +
"\n";
173 ret +=
toStr(n->
r, prefix +
"| ");
175 ret +=
toStr(n->
l, prefix +
"| ");
std::string toStr() const
Prints an ASCII representation of the expression tree.
std::array< OpSearch, uNeg+1 > ops
Operator list.
panic_if(!root,"Invalid expression\n")
Node * parse(std::string expr)
Parse and create nodes from string.
MathExpr(std::string expr)
std::function< double(std::string)> EvalCallback
std::string toStr() const
double eval(EvalCallback fn) const
Evaluates the expression.