-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEvaluator.cs
42 lines (37 loc) · 1.19 KB
/
Evaluator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
using System.Collections.Generic;
namespace Calculator
{
public class Evaluator
{
readonly Queue<Token> postfixExpression;
public Evaluator (Queue<Token> postfixExpression)
{
this.postfixExpression = postfixExpression;
}
public double Evaluate()
{
Stack<Token> evaluationStack = new Stack<Token> ();
foreach (var token in postfixExpression) {
if (token.Type == TokenType.Number) {
evaluationStack.Push (token);
} else if (token.Type == TokenType.Operator) {
double result;
Token temp = evaluationStack.Pop ();
Operator op = new Operator (token);
if (op.Op.Value == "#" || op.Op.Value == "@") {
result = op.Operation (double.Parse (temp.Value));
} else {
string val1 = evaluationStack.Peek ().Value;
result = op.Operation (Double.Parse (evaluationStack.Pop ().Value), Double.Parse (temp.Value));
}
evaluationStack.Push (new Token (result.ToString ()));
} else if (token.Type == TokenType.Function) {
double result = Function.Call (token.Value, evaluationStack);
evaluationStack.Push (new Token (result.ToString ()));
}
}
return Double.Parse (evaluationStack.Pop ().Value);
}
}
}