Convert a string expression into a lambda expression

Many times when building a solution that contains a lambda expression, we might ask ourselves how it is possible to allow the user to manipulate the actual expression on runtime, and if it can be accomplished  using C#/VB.NET (and other .NET targeting languages). The answer to this is yes, and in fact, it does not require that much referencing.

You might think that you need a compiler, specifically an expression compiler in order to proceed. This is true, however, it is important to not to lose the hope, since a compiler, a specialized program, is a wide concept.

The compiler we are to use to evaluate string expressions understands two main things: addition/multiplication/etc. of numbers and inserting the value of a variable into the expression (of course, it can do some other things too, however, they are not required in this tutorial, and, they do not hurt the performance in any way). It is called Mathos Parser. Below, some steps of how you can implement the lambda evaluator.

le1

  1. If you use C# environment, you can simply create a new class in your project called Parser.cs and copy-paste the source code of Mathos Parser (it is less than 500 lines of code). Do not worry, you will hopefully not need to add any other references to your project since it is not that dependent on other components. If you are using VB.NET (or any other .NET targeting language), you will need to add Mathos Parser as a reference in your project.
  2. Now, add these LamdaEvaluator functions as they are in the code below.

The first method takes only one parameter, x, so every time you construct an expression, make sure you use x as the variable. Notice that this variable can be changed, specially on runtime, which allows the target user to choose which variable he or she prefers the most.

The second method supports infinite number of parameters to be used by the function, so when referring to a particular variable in the array, please use x0, x1, etc. However, if you know that you only want to use a constant number of variables, you can always assign them different letters.

le2

In a recent article, this principle was used to evaluate integrals using numerical approximation algorithms.

You can download the code here: https://mathosparser.codeplex.com/releases/view/114265

I hope this article was to some help!

/Artem

Comments are closed.