Expression evaluator in 15 minutes with Irony & Dlr
One use for IronPython in .NET applications is as an embedded engine for expression evaluation:
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.Piter has used the DLR, along with a C# parser library called Irony (which he has also used to create Script.NET), to create a string expression evaluator:
.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.
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).
Comments
Post a Comment