예제 #1
0
        private static void HandleSpecialCommand(IEvaluationContext context, string input)
        {
            switch (input.ToUpper())
            {
            case "$RAD":
                context.DegreeMode = DegreesMode.Radians;
                Console.WriteLine("Degree mode set to radians.");
                break;

            case "$DEG":
                context.DegreeMode = DegreesMode.Degrees;
                Console.WriteLine("Degree mode set to degrees.");
                break;

            case string set when set.StartsWith("$SET"):
                Console.WriteLine($"Mode={context.DegreeMode}");

                break;

            case "$VAR":
                foreach (var name in context.Variables)
                {
                    Console.WriteLine($"{name}={context.GetVariableValue(name)}");
                }
                break;

            case "$CONST":
                foreach (var name in context.Constants)
                {
                    Console.WriteLine($"{name}={context.GetVariableValue(name)}");
                }
                break;

            case "$HELP":
                Console.WriteLine("CalcX is a normal calculator, with support for functions and variables.");
                Console.WriteLine("Meta commands start with '$': $rad, $deg, $var, $const, $set");
                break;

            default:
                Console.WriteLine("Unknown directive. Enter $help for some help.");
                break;
            }
        }
예제 #2
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());
        }