我正在翻译表达式树,我想知道是否有现有的库或技术适用于减少/优化树中的操作。
例如,我希望能够折叠一系列顺序否定操作,如下所示:
arg => !!!!!!!(getValue(arg))
reduces to arg => !getValue(arg)
...或者将一个否定后跟一个相等运算变成一个不等于运算:
arg => !(getValue(arg) == 3)
reduces to arg => getValue(arg) != 3
...或将德摩根定律应用于一般的逻辑表达式:
arg => !(getValue(arg) < 3 || getValue(arg) >= 5))
reduces to arg => getValue(arg) >= 3 && getValue(arg) < 5
[为简洁起见,我使用了上述简化格式的 lambda 表达式。]
我知道这些工具不能适用于表达式树的所有可能评估,但似乎它们对严格使用逻辑运算的表达式树类有用。
是否有关于构建执行这些任务的表达式树评估器的现有引用?
最佳答案
看起来没有可重用的 .NET Framework 组件来解决问题中提出的要求。但是,Andrey Shchekin's tool reference为如何编写所需的组件提供了很好的引用。
这是一个解决顺序 Not() 运算符的取消、将 Not() 运算符分配到二进制表达式以及 De Morgan 定律的应用的片段。
public class NotCollapser : ExpressionVisitor
{
// Incomplete list; others removed for brevity.
private static readonly IDictionary<ExpressionType, Func<BinaryExpression, BinaryExpression>> NotDistributionMap =
{
{ ExpressionType.Equal, e => Expression.MakeBinary(ExpressionType.NotEqual, e.Left, e.Right) },
{ ExpressionType.NotEqual, e => Expression.MakeBinary(ExpressionType.Equal, e.Left, e.Right) },
{ ExpressionType.GreaterThan, e => Expression.MakeBinary(ExpressionType.LessThanOrEqual, e.Left, e.Right) },
{ ExpressionType.AndAlso, e => Expression.MakeBinary(ExpressionType.OrElse, Expression.Not(e.Left), Expression.Not(e.Right)) },
{ ExpressionType.OrElse, e => Expression.MakeBinary(ExpressionType.AndAlso, Expression.Not(e.Left), Expression.Not(e.Right)) }
};
protected override Expression VisitUnary(UnaryExpression expression)
{
if (expression.NodeType == ExpressionType.Not)
{
if (expression.Operand.NodeType == ExpressionType.Not)
{
return Visit((expression.Operand as UnaryExpression).Operand);
}
if (NotDistributionMap.ContainsKey(expression.Operand.NodeType))
{
var distribute = NotDistributionMap[expression.Operand.NodeType];
return Visit(distribute(expression.Operand as BinaryExpression));
}
}
return base.VisitUnary(expression);
}
}
关于.net - 是否有现有的库/技术来减少 .NET 表达式树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11821363/