All pastes #120048 Raw Edit

freeone3000

public text v1 · immutable
·published 2006-08-07 03:57 UTC
rendered paste body
    public class PrefixParser : Parser
    {
        private Dictionary<string, double> variables = new Dictionary<string, double>();
        private Stack<double> operands = new Stack<double>();
        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<string, double> getVariables()
        {
            return variables;
        }
    }