/// <summary> /// Evaluates the expression /// </summary> /// <returns>The result of evaluation</returns> public double Evaluate() { //Create a clone of expression because we don't want to mess with it CloneableStack <Symbol> expr = expression.Clone(); Stack <Symbol> tempStack = new Stack <Symbol>(); double[] values; while (expr.Count() > 0) { if (!expr.Peek().isOperator) { tempStack.Push(expr.Pop()); } else { //Pop values, tempStack should only be 0 op symbols values = new double[expr.Peek().nOps]; for (int i = 0; i < values.Length; i++) { values[i] = tempStack.Pop().eval(null); } tempStack.Push(new Symbol(expr.Pop().eval(values))); } } return(tempStack.Pop().eval(null)); }
/// <summary> /// Converts an infix expression represented an array of strings to a /// corresponding RPN expression as a stack. /// </summary> /// <param name="inputTokens"></param> /// <returns></returns> private CloneableStack <Symbol> InfixToRPN(string[] inputTokens) { //ArrayList outList = new ArrayList(); CloneableStack <Symbol> result = new CloneableStack <Symbol>(0); Stack <string> stack = new Stack <string>(); //for all the input tokens read the next token foreach (string token in inputTokens) { if (IsOperator(token)) { //If token is an operator while (stack.Count != 0 && IsOperator(stack.Peek())) { if ((IsAssociative(token, LEFT_ASSOC) && CmpPrecedence(token, stack.Peek()) <= 0) || (IsAssociative(token, RIGHT_ASSOC) && CmpPrecedence(token, stack.Peek()) < 0)) { result.Push(ToSymbol(stack.Pop())); continue; } break; } //Push the new operator on the stack stack.Push(token); } else if (token.Equals("(")) { stack.Push(token); } else if (token.Equals(")")) { while (stack.Count != 0 && !stack.Peek().Equals("(")) { result.Push(ToSymbol(stack.Pop())); } stack.Pop(); } else { result.Push(ToSymbol(token)); } } while (stack.Count != 0) { result.Push(ToSymbol(stack.Pop())); } CloneableStack <Symbol> actualResult = new CloneableStack <Symbol>(result.Count()); while (result.Count() > 0) { actualResult.Push(result.Pop()); } return(actualResult); }
public void Pop() { curIndent -= GetIndent(indentStack.Pop()); Update(); }