Retab calc3.cc.

This commit is contained in:
yhirose 2015-06-14 08:06:09 -04:00
parent b0f34248ab
commit 427bbda5a7

View File

@ -19,25 +19,25 @@ int main(int argc, const char** argv)
return 1; return 1;
} }
function<long (const Ast&)> eval = [&](const Ast& ast) { function<long (const Ast&)> eval = [&](const Ast& ast) {
if (ast.name == "NUMBER") { if (ast.name == "NUMBER") {
return stol(ast.token); return stol(ast.token);
} else { } else {
const auto& nodes = ast.nodes; const auto& nodes = ast.nodes;
auto result = eval(*nodes[0]); auto result = eval(*nodes[0]);
for (auto i = 1u; i < nodes.size(); i += 2) { for (auto i = 1u; i < nodes.size(); i += 2) {
auto num = eval(*nodes[i + 1]); auto num = eval(*nodes[i + 1]);
auto ope = nodes[i]->token[0]; auto ope = nodes[i]->token[0];
switch (ope) { switch (ope) {
case '+': result += num; break; case '+': result += num; break;
case '-': result -= num; break; case '-': result -= num; break;
case '*': result *= num; break; case '*': result *= num; break;
case '/': result /= num; break; case '/': result /= num; break;
} }
} }
return result; return result;
} }
}; };
peg parser( peg parser(
" EXPRESSION <- _ TERM (TERM_OPERATOR TERM)* " " EXPRESSION <- _ TERM (TERM_OPERATOR TERM)* "