Separated expression string processing to its own method and created basic REPL

This commit is contained in:
Dmitriy Shishkov 2021-08-08 19:03:15 +03:00
parent 4a27d77713
commit 8234e92ce1
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060

View File

@ -8,60 +8,76 @@ namespace calculator
static void Main(string[] args) static void Main(string[] args)
{ {
if (args.Length == 0) if (args.Length == 0)
Console.WriteLine("REPL is not ready yet. Please, provide mathematic expression as an argument"); {
else string input = readREPL();
try while (input != null)
{ {
string[] expr = args[0].Split(); writeREPL(evaluate(input));
Stack<double> st = new Stack<double>(); input = readREPL();
}
}
else
{
writeREPL(evaluate(args[0]));
}
}
for (int i = 0; i < expr.Length; i++) static private double evaluate(string s)
{
try
{
string[] expr = s.Split();
Stack<double> st = new Stack<double>();
for (int i = 0; i < expr.Length; i++)
{
object val = convertOne(expr[i]);
if (val is double number)
st.Push(number);
else if (val is char oper)
{ {
object val = convertOne(expr[i]); try
if (val is double number)
st.Push(number);
else if (val is char oper)
{ {
try double b = st.Pop();
double a = st.Pop();
switch (oper)
{ {
double b = st.Pop(); case '+':
double a = st.Pop(); st.Push(a + b);
switch (oper) break;
{ case '-':
case '+': st.Push(a - b);
st.Push(a + b); break;
break; case '*':
case '-': st.Push(a * b);
st.Push(a - b); break;
break; case '/':
case '*': st.Push(a / b);
st.Push(a * b); break;
break; case '^':
case '/': st.Push(Math.Pow(a, b));
st.Push(a / b); break;
break; default:
case '^': throw new Exception("Got unknown operator");
st.Push(Math.Pow(a, b));
break;
default:
throw new Exception("Got unknown operator");
}
}
catch (InvalidOperationException)
{
throw new Exception(oper + " operation requires two operands");
} }
} }
else throw new Exception("Stack corrupted"); catch (InvalidOperationException)
{
throw new Exception(oper + " operation requires two operands");
}
} }
else throw new Exception("Stack corrupted");
}
Console.WriteLine(st.Pop()); return st.Pop();
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine(e.Message); Console.WriteLine(e.Message);
} Environment.Exit(1);
return -1;
}
} }
static private object convertOne(string s) static private object convertOne(string s)
@ -71,5 +87,29 @@ namespace calculator
else if (s.Length == 1) return s[0]; else if (s.Length == 1) return s[0];
else throw new Exception("Got multiple characters operator"); else throw new Exception("Got multiple characters operator");
} }
static private string readREPL()
{
Console.Write(">> ");
string input = Console.ReadLine();
switch (input)
{
case "exit":
case "exit()":
case "quit":
case "quit()":
case "q":
case "":
return null;
default:
return input;
}
}
static private void writeREPL<T>(T o)
{
Console.WriteLine(o);
}
} }
} }