Practice · 1 of 3
Constant-folding visitor
CHALLENGE
Difficulty: advanced+25 XP
Implement class FoldVisitor : ExpressionVisitor that replaces any BinaryExpression with two Constant operands by a single Constant of its computed value (ints only; support Add, Multiply, Subtract). Folding must be RECURSIVE: once inner binary nodes fold to constants, the enclosing binary folds too. The test builds the tree with explicit Expression.* calls because the compiler already constant-folds lambda literals at compile time — x => 2 + 3 + x arrives as (5 + x) with nothing left to fold. Also implement static Expression<Func<int,int>> FoldExpr(Expression<Func<int,int>> e) returning the visited (folded) expression.
Press Submit to check your solution.
Back to lesson: Practice: Expression drills