# Angel \”Java\” Lopez on Blog

## January 30, 2009

### Dynamic Expressions Example

Filed under: .NET, C Sharp, Programming Languages — ajlopez @ 6:26 am

Yesterday, I was preparing a presentation for today, explaining lambda calculus, its history, and lambda application in languages. At the end of presentation, I’ll discuss lambda ideas in .NET: delegates, lambda notation, and lambda expression.

During a quick research, I found a really cool implementation of dynamic expression parsing, in the example:

DynamicLinq.cs

That code points as source the “the Gu” blog post:

Dynamic LINQ (Part 1- Using the LINQ Dynamic Query Library)

The code is included in the DynamicQuery directory in:

C# Dynamic Query Library (included in the -LinqSamples-DynamicQuery directory)

My initial idea was to write a formula graph winform app, using System.Linq.Expressions. But the above implementation has a notable feature: instead of buildin an expression tree composing a expressions, it takes an string (!!!) and parse on the fly, converting to a compiled version.

OK, this trick is used by many Linq query implementations, but I didn’t know that the code samples from Microsoft include this code.

Using the DynamicLinq.cs, I was able to create a Win Form app:

Note that you can use classes from .NET. “x” is the parameter I use to calculate the formula.

This is a key code in the Calculator.cs file:

```        public Delegate CompileFormula(string formula)
{
ParameterExpression x = Expression.Parameter(typeof(double), "x");
LambdaExpression e = DynamicExpression.ParseLambda(new ParameterExpression[] { x }, null, formula);
return e.Compile();
}
```

The compiled Delegate, can be invoked, provided the “x” parameter value:

```        public double[] Calculate(Delegate formula, double from, double to, double step)
{
List<double> values = new List<double>();

for (double x = from; x <= to; x += step)

return values.ToArray();
}```

You can download this sample code from:

Another dynamic implementation:

Some ideas:

- Extend the example to 3D (I could use the F#/DirectX visualization demo as a base code)

- Send a formula as text, to be processed in a distributed application, grid, or HPC cluster.

- Code kata writing a .Parse and .Compile to any of my scripting languages

If you need more power, the next level of dynamic languages and their compilation, using .NET, is the Microsoft.Scripting namespace in IronPython source code:

http://www.codeplex.com/IronPython/SourceControl

Introductions to IronPython, DLR initiative:

Related links about lambda, Dynamic Language Runtime, and dynamic languages in general:

Angel “Java” Lopez
http://www.ajlopez.com/en