Beispiel #1
0
        public double Calculate(IEnumerable <Token> tokens)
        {
            var stack = new Stack <double>(16);

            foreach (var token in tokens)
            {
                switch (token)
                {
                case NumberToken n:
                    stack.Push(n.Value);
                    break;

                case VariableToken v:
                    stack.Push(Context.GetVariableValue(v.Text));
                    break;

                case OperatorToken op:
                    stack.Push(OperatorMap[op.Text].Eval(null, stack));
                    break;

                case FunctionToken func:
                    var count = Context.GetFunctionArgumentCount(func.Text);
                    var args  = new List <double>(count);
                    for (int i = 0; i < count; i++)
                    {
                        args.Add(stack.Pop());
                    }

                    stack.Push(Context.EvalFunction(func.Text, args.ToArray()));
                    break;

                default:
                    throw new InvalidOperationException();
                }
            }

            return(stack.Peek());
        }