Home Ask Login Register

Developers Planet

Your answer is one click away!

Max February 2016

How to Assign values to Expression tree parameters and evaluate

I'm hoping some kind soul here might be able to help me with this. Essentially, I've got a random function represented as an expression tree in C#. I would like for it to consist of variables, and for me to be able to evaluate it based on the values I assign the variables. So, in its simplest form, the tree might look like:

ParameterExpression a = Expression.Variable(typeof(double), "a");
ParameterExpression b = Expression.Variable(typeof(double), "b");
Expression function = Expression.MakeBinary(ExpressionType.Subtract, a, b);

so that the function looks like (a - b). I then wish to evaluate this, which I can do as:

Expression.Lambda<Func<double, double, double>>(function, a, b).Compile()(5.0, 3.0);

The problems I have are:

  1. The function is randomly generated, so I do not know how many variables it has. I only have a list of possible variables
  2. I do not know in what order the variables are used

So is there a way I can declare, much like normal code, a = 4 and b = 2 and then compile the function based on those declarations?

If not, then what other alternatives are there? So far I have:

  • Loop through the tree (using ExpressionVisitor) and replace, say a with just Expression.Constant(4.0)
  • Go down the route of:

    ParameterExpression variableExpr = Expression.Variable(typeof(double), "a");
    Expression assignExpr = Expression.Assign(variableExpr,Expression.Constant(4.0));
    Expression a = Expression.Block(new ParameterExpression[] { variableExpr }, assignExpr);
    [...]
    Expression.Lambda<Func<double>>(function).Compile()();
    

    but I would like to try and avoid adding block segments to the function if possible.

Any help and pointers would be greatly appreciated

Thanks

Answers


svick February 2016

I do not know how many variables it has.

You have the list of all possible variables. Because of that, I think the simplest solution would be to always assume all variables are used. So, you generate a lambda that has all the variables as parameters and then call it while passing values to all parameters.

I do not know in what order the variables are used

I don't see how does that matter. The order of parameters when declaring the function and when calling the function have to match, but you control both, so that shouldn't be a problem.

Post Status

Asked in February 2016
Viewed 3,745 times
Voted 9
Answered 1 times

Search




Leave an answer


Quote of the day: live life