What does Expression.Reduce() do?

d.. picture d.. · Jan 10, 2010 · Viewed 8.9k times · Source

I've been working with expression trees for a few days now and I'm curious to know what Expression.Reduce() does. The msdn documentation is not very helpful as it only states that it "reduces" the expression. Just in case, I tried an example (see below) to check if this method included mathematical reduction, but this doesn't seem to be the case.

Does anyone know what this method does and is it possible to provide a quick example showing it in action? Any good resources out there?

static void Main(string[] args)
{
    Expression<Func<double, double>> func = x => (x + x + x) + Math.Exp(x + x + x);
    Console.WriteLine(func);
    Expression r_func = func.Reduce();
    Console.WriteLine(r_func); // This prints out the same as Console.WriteLine(func)
}

Answer

Alexandra Rusina picture Alexandra Rusina · Jan 11, 2010

The document you need to look at is expr-tree-spec.pdf.

This is the specification for the expression trees. Read the "2.2 Reducible Nodes" and "4.3.5 Reduce Method" sections.

Basically, this method is intended for people implementing or porting their dynamic langauges to .NET. So that they can create their own nodes that can "reduce" to standard expression tree nodes and can be compiled. There are some "reducible" nodes in the expression trees API, but I don't know whether you can get any practical examples (since all standard expression nodes compile anyway, as the end-user you probably do not care whether they are "reduced" behind the scenes or not).

Yes, MSDN documentation is very basic in this area, because the main source of info and docs for language implementers is on GitHub, with the documentation in its own subfolder.