public class PrefixParser : Parser { private Dictionary variables = new Dictionary(); private Stack operands = new Stack(); private string op = ""; public double evaluate(string str) { str = str.Trim(); for (int i = 0; i < str.Length; i++) { if (Common.isDigit(str[i])) { operands.Push(str[i]); if (operands.Count == 2 && op != "") { operands.Push(applyOperator()); } } else { if (op != "") throw new ParserException("Two operands cannot be specified in sequence."); } } return operands.Pop(); } private double applyOperator() { switch (op) { case "/": return operands.Pop() / operands.Pop(); case "+": return operands.Pop() + operands.Pop(); case "-": return operands.Pop() - operands.Pop(); case "*": return operands.Pop() * operands.Pop(); case "^": return (long)operands.Pop() ^ (long)operands.Pop(); case "|": return (long)operands.Pop() | (long)operands.Pop(); case "&": return (long)operands.Pop() & (long)operands.Pop(); case "pow": return Math.Pow(operands.Pop(), operands.Pop()); default: throw new ParserException("Unrecognized operand " + op); } } public Dictionary getVariables() { return variables; } }