Expression evaluator in 15 minutes with Irony & Dlr
Evaluation of a string expression to a value is a common programming task. Almost any college course in informatics includes this excercise. It involves implementing some fundamental algorithms and structures such as: recursive-descent parser, regexp matching, traversal algorithms, syntax tree, hash-tables, etc. And for sure it should be done on some pure programming language such as ANSI C or Pascal.
.NET Framework brought a lot of in-box algorithms and structures which simplifies the usual live of software developer. However it is still a good excercise to evaluate a string expression, say 2+(4*5)^12.
But fortunately there are some new tools that facilitate producing language parsers and their interpreters/compilers. If you are interested in such kind of tasks I would suggest you to look at following libraries:
DLR will be a part of the upcoming .NET Framework 4.0 and C#. It is a base for Iron languages: IronPython and IronRuby.
Irony is a library for creating parsers in C#. It is very convenient and efficient.
About a year ago I’ve posted few posts about using DLR for creating dynamic languages:
Also I’ve used Irony to create Script.NET.
So today I’ve looked at the recent releases for both of these tools and tried to create string expression evaluator once again. And it took aproximately 15 minutes! Wow!
Irony already had examples of parsers for arithmetic expressions and I’ve used them. The next step is to evaluate parsed syntax tree. For these purpose one may use very convenient Expression class which comes as a part of DLR under Microsoft.Linq.Expressions namespace.
So, please take a look at the results. Bin+Src.
This console application will accept a single line valid string expression on natural numbers. It supports following operations: +,-,*,/,** (Pow).