From c74d8917f3890ec1ed9bab158ccea309cb05e0cd Mon Sep 17 00:00:00 2001 From: Adrian Kummerlaender Date: Fri, 31 Mar 2017 19:18:35 +0200 Subject: Implement primitives as lambda expressions in an unordered set --- repl.cc | 115 +++++++++++++++++++++++++++++++++++++--------------------------- 1 file changed, 66 insertions(+), 49 deletions(-) diff --git a/repl.cc b/repl.cc index a44a733..31d8b07 100644 --- a/repl.cc +++ b/repl.cc @@ -4,6 +4,9 @@ #include #include +#include +#include + #include #include @@ -15,65 +18,79 @@ bool is_number(const std::string& token) { ); } -bool is_primitive(const std::string& token) { - return token == "+" - || token == "-" - || token == "*" - || token == "." - || token == "swp" - || token == "dup" - || token == "del"; -} - -void process(std::stack& stack, const std::string& token) { - if ( token == "+" ) { - const int b = stack.top(); - stack.pop(); - const int a = stack.top(); - stack.pop(); +int main(int, char*[]) { + std::stack stack; + std::string token; - stack.push(a + b); - } else if ( token == "-" ) { - const int b = stack.top(); - stack.pop(); - const int a = stack.top(); - stack.pop(); + std::unordered_map> builtin{ + { + "+", [&stack]() { + const int b = stack.top(); + stack.pop(); + const int a = stack.top(); + stack.pop(); - stack.push(a - b); - } else if ( token == "*" ) { - const int b = stack.top(); - stack.pop(); - const int a = stack.top(); - stack.pop(); + stack.push(a + b); + } + }, + { + "-", [&stack]() { + const int b = stack.top(); + stack.pop(); + const int a = stack.top(); + stack.pop(); - stack.push(a * b); - } else if ( token == "." ) { - std::cout << stack.top() << std::endl; - } else if ( token == "swp" ) { - const int b = stack.top(); - stack.pop(); - const int a = stack.top(); - stack.pop(); + stack.push(a - b); + } + }, + { + "*", [&stack]() { + const int b = stack.top(); + stack.pop(); + const int a = stack.top(); + stack.pop(); - stack.push(b); - stack.push(a); - } else if ( token == "dup" ) { - stack.push(stack.top()); - } else if ( token == "del" ) { - stack.pop(); - } -} + stack.push(a * b); + } + }, + { + ".", [&stack]() { + std::cout << stack.top() << std::endl; + } + }, + { + "swp", [&stack]() { + const int b = stack.top(); + stack.pop(); + const int a = stack.top(); + stack.pop(); -int main(int, char*[]) { - std::stack stack; - std::string token; + stack.push(b); + stack.push(a); + } + }, + { + "dup", [&stack]() { + stack.push(stack.top()); + } + }, + { + "del", [&stack]() { + stack.pop(); + } + } + }; while ( std::cin.good() ) { if ( std::cin >> token ) { if ( is_number(token) ) { stack.push(std::atoi(token.c_str())); - } else if ( is_primitive(token) ) { - process(stack, token); + } else { + const auto& impl = builtin.find(token); + + if ( impl != builtin.end() ) { + impl->second(); + } } } } -- cgit v1.2.3