简体   繁体   中英

C# expression trees for a calculator

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.

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.

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM