|
|
Invisible wrote:
> #include <iostream>
> #include <vector>
> #include <string>
>
> using namespace std;
>
> bool StackCheck(vector<int> stack, int min)
> {
> if (stack.size() >= min) return true;
>
> cout << "Stack underflow." << endl;
> return false;
> }
>
> void Add(vector<int>& stack)
> {
> if (!StackCheck(stack, 2)) return;
>
> int x = stack.back(); stack.pop_back();
> int y = stack.back(); stack.pop_back();
> stack.push_back(x + y);
> }
>
> void Sub(vector<int>& stack)
> {
> if (!StackCheck(stack, 2)) return;
>
> int x = stack.back(); stack.pop_back();
> int y = stack.back(); stack.pop_back();
> stack.push_back(x - y);
> }
>
> int main()
> {
> cout << "Calc #01" << endl;
>
> vector<int> stack;
> string cmd;
>
> while (true)
> {
> for (int i=0; i<stack.size(); i++)
> cout << "[" << i << "]: " << stack[i] << endl;
>
> cout << "Calc> ";
> cin >> cmd;
>
> if (cmd == "^") break;
> if (cmd == "+") {Add(stack); continue;}
> if (cmd == "-") {Sub(stack); continue;}
> stack.push_back(1);
> }
>
> cout << "Exit." << endl;
> }
module Main (main) where
main = do
putStrLn "Calc #01"
main_loop []
main_loop stack = do
mapM_ (\(n,v) -> putStrLn $ "[" ++ show n ++ "]: " ++ show v) (zip
[0..] stack)
putStr "Calc> "
cmd <- getLine
case cmd of
"^" -> return ()
"+" -> binary (+) stack
"-" -> binary (-) stack
_ -> main_loop (1:stack)
binary fn stack = case stack of
x:y:zs -> do main_loop ((fn x y) : zs)
_ -> do putStrLn "Stack underflow."; main_loop stack
Somehow... it seems so much easier in Haskell. ;-)
Post a reply to this message
|
|