aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdrian Kummerlaender2017-03-30 22:31:16 +0200
committerAdrian Kummerlaender2017-03-30 22:32:06 +0200
commit5046728ca7285f2a2139c14252ee657c0ab3abcf (patch)
tree5351d0f4c09f893e1ee7a7efa1361e21db2c8900
downloadslang-5046728ca7285f2a2139c14252ee657c0ab3abcf.tar
slang-5046728ca7285f2a2139c14252ee657c0ab3abcf.tar.gz
slang-5046728ca7285f2a2139c14252ee657c0ab3abcf.tar.bz2
slang-5046728ca7285f2a2139c14252ee657c0ab3abcf.tar.lz
slang-5046728ca7285f2a2139c14252ee657c0ab3abcf.tar.xz
slang-5046728ca7285f2a2139c14252ee657c0ab3abcf.tar.zst
slang-5046728ca7285f2a2139c14252ee657c0ab3abcf.zip
Minimal stack calculator REPL implementation
-rw-r--r--CMakeLists.txt16
-rw-r--r--repl.cc67
2 files changed, 83 insertions, 0 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 0000000..4deaa23
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 2.8)
+project(lang)
+
+set(
+ CMAKE_CXX_FLAGS
+ "${CMAKE_CXX_FLAGS} -std=c++14 -W -Wall -Wextra -Winline -pedantic"
+)
+
+include_directories(
+ src/
+)
+
+add_executable(
+ repl
+ repl.cc
+)
diff --git a/repl.cc b/repl.cc
new file mode 100644
index 0000000..616d0f3
--- /dev/null
+++ b/repl.cc
@@ -0,0 +1,67 @@
+#include <iostream>
+
+#include <stack>
+#include <string>
+#include <algorithm>
+
+#include <cctype>
+#include <cstdlib>
+
+bool is_number(const std::string& token) {
+ return std::all_of(
+ token.begin(),
+ token.end(),
+ [](char c) { return std::isdigit(c); }
+ );
+}
+
+bool is_primitive(const std::string& token) {
+ return token == "+"
+ || token == "-"
+ || token == "*"
+ || token == ".";
+}
+
+void process(std::stack<int>& stack, const std::string& token) {
+ if ( token == "+" ) {
+ 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);
+ } else if ( token == "*" ) {
+ 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;
+ }
+}
+
+int main(int, char*[]) {
+ std::stack<int> stack;
+ std::string token;
+
+ 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);
+ }
+ }
+ }
+
+ return 0;
+}