C# expression trees for a calculator

2.4k views Asked by At

I'm a C# newbie. I want to write a calculator app in C#. Would C# expression trees be a good way to go for the guts of it? (That is, the part that takes a series of keypresses and turns them into an expression that the calculator can evaluate and display on the screen . . . or graph.)

I'll want to include the standard math functions, including trig, logs, exponents, etc.

2

There are 2 answers

0
mqp On BEST ANSWER

Since your language for mathematical expressions will surely be much, much simpler than C#, I suspect that trying to reuse the framework expression tree classes to represent your ASTs will be overkill and probably a recipe for frustration; if you look at those classes, you'll see a lot of properties and functionality that would be totally irrelevant to your little language. I'd roll your own if I were you.

0
GreyCloud On

you might be able to learn from this project, there are good tutorials aobut how it was made

Have you seen http://ncalc.codeplex.com ?

It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse: Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");

e.Parameters["Pi2"] = new Expression("Pi * Pi"); e.Parameters["X"] = 10;

e.EvaluateParameter += delegate(string name, ParameterArgs args) { if (name == "Pi") args.Result = 3.14; };

Debug.Assert(117.07 == e.Evaluate());

It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.

It also supports logical operators, date/time's strings and if statements.