I try to return vectors' scalar product using expression trees, but I can not loop into arrays, can u help me? The task description and code please see below:
public class CodeGeneration
{
public static Func<T[], T[], T> GetVectorMultiplyFunction<T>() where T : struct
{
// TODO : Implement GetVectorMultiplyFunction<T>.
// Input
ParameterExpression arr1 = Expression.Parameter(typeof(T[]), "first");
ParameterExpression arr2 = Expression.Parameter(typeof(T[]), "second");
ParameterExpression result = Expression.Parameter(typeof(T), "result");
// Creating a label to jump to from a loop.
LabelTarget label = Expression.Label(typeof(int));
// Creating a method body
BlockExpression block = Expression.Block(
// Adding a local variable.
new[] { result },
// Assigning a constant to a local variable: result = 1
Expression.Assign(result, Expression.Constant(0)),
// Adding a loop.
Expression.Loop(
// Adding a conditional block into the loop.
Expression.IfThenElse(
// ..........................
// I can not write the iteration for input arrays like the method below:
// ..........................
Expression.Break(label, result)
),
// Label to jump to.
label
)
);
}
// solution simple
public static int MultiplyVectors(int[] first, int[] second)
{
int result = 0;
for (int i = 0; i < first.Length; i++)
{
result += first[i] * second[i];
}
return result;
}
If all you need is an expression, then for "single" lambda statements you can just declare an expression:
But it sounds like this is homework problem, so at least you can use the above for testing.
You need to declare a loop variable, and increment it in the loop. ~ How to create a loop expression tree
You will also need
Expression.ArrayAccessto retrieve value of an array.You also need to get the array length. Probably you can simply use
Expression.ArrayLength, but because you are using generics, it might be safer to retrieve theLengthproperty ~ Expression getting length of an arrayPutting this all together:
With the
MultuplyVectorsdeclared above, you can test with (note I changed the types todoubleto demo genericT):console output:
Note: in visual studio debugger, there is a debug (visual studio runtime) only property on
Expressioncalled DebugView which will explain how the expression is defined. For example