我的程序的目标是显示数学表达式的符号导数。在创建代表衍生产品的新树后,可能会留下多余的条款。
例如,以下树未简化。
Example of binary expression tree
树from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy
extensions = [
Extension('proto_mpeg_computation', ['proto_mpeg_computation.pyx'],
include_dirs=[numpy.get_include()]
),
]
setup(
name = "proto_mpeg_x",
ext_modules = cythonize(extensions)
)
可以重写为0 + 5 * (x * 5)
我的程序使用许多25 * x
和if
块来通过检查常量乘以常量等来减少树。然后,它相应地重新排列子树。
这是我的递归函数的一小部分,简化了树:
else
除了我需要调用它几次以确保树完全缩小(减少开启另一种减少的可能性)之外,该功能工作得很好。然而,它长达200行且不断增长,这使我相信必须有更好的方法来实现这一目标。
答案 0 :(得分:1)
解决此问题的一种典型方法是visitor pattern。任何时候你需要走一个递归结构,在每个节点上应用逻辑,这取决于节点的“类型”,这个模式是一个很好用的工具。
对于这个特定问题,特别是在Java中,我首先将表达式“抽象语法树”更直接地表示为类型层次结构。
我已经把一个简单的例子放在一起,假设你的AST处理+, - ,*,/以及文字数和命名变量。我已将Visitor
称为Folder
---我们有时会将此名称用于替换(“折叠”)子树的访客。 (想一想:编译器中的优化或去糖通过。)
处理“我需要有时重复简化”的技巧是进行深度优先遍历:在简化父母之前,所有孩子都要完全简化。
以下是示例(免责声明:我讨厌Java,因此我不保证这是该语言中最“惯用”的实现):
interface Folder {
// we could use the name "fold" for all of these, overloading on the
// argument type, and the dispatch code in each concrete Expression
// class would still do the right thing (selecting an overload using
// the type of "this") --- but this is a little easier to follow
Expression foldBinaryOperation(BinaryOperation expr);
Expression foldUnaryOperation(UnaryOperation expr);
Expression foldNumber(Number expr);
Expression foldVariable(Variable expr);
}
abstract class Expression {
abstract Expression fold(Folder f);
// logic to build a readable representation for testing
abstract String repr();
}
enum BinaryOperator {
PLUS,
MINUS,
MUL,
DIV,
}
enum UnaryOperator {
NEGATE,
}
class BinaryOperation extends Expression {
public BinaryOperation(BinaryOperator operator,
Expression left, Expression right)
{
this.operator = operator;
this.left = left;
this.right = right;
}
public BinaryOperator operator;
public Expression left;
public Expression right;
public Expression fold(Folder f) {
return f.foldBinaryOperation(this);
}
public String repr() {
// parens for clarity
String result = "(" + left.repr();
switch (operator) {
case PLUS:
result += " + ";
break;
case MINUS:
result += " - ";
break;
case MUL:
result += " * ";
break;
case DIV:
result += " / ";
break;
}
result += right.repr() + ")";
return result;
}
}
class UnaryOperation extends Expression {
public UnaryOperation(UnaryOperator operator, Expression operand)
{
this.operator = operator;
this.operand = operand;
}
public UnaryOperator operator;
public Expression operand;
public Expression fold(Folder f) {
return f.foldUnaryOperation(this);
}
public String repr() {
String result = "";
switch (operator) {
case NEGATE:
result = "-";
break;
}
result += operand.repr();
return result;
}
}
class Number extends Expression {
public Number(double value)
{
this.value = value;
}
public double value;
public Expression fold(Folder f) {
return f.foldNumber(this);
}
public String repr() {
return Double.toString(value);
}
}
class Variable extends Expression {
public Variable(String name)
{
this.name = name;
}
public String name;
public Expression fold(Folder f) {
return f.foldVariable(this);
}
public String repr() {
return name;
}
}
// a base class providing "standard" traversal logic (we could have
// made Folder abstract and put these there
class DefaultFolder implements Folder {
public Expression foldBinaryOperation(BinaryOperation expr) {
// recurse into both sides of the binary operation
return new BinaryOperation(
expr.operator, expr.left.fold(this), expr.right.fold(this));
}
public Expression foldUnaryOperation(UnaryOperation expr) {
// recurse into operand
return new UnaryOperation(expr.operator, expr.operand.fold(this));
}
public Expression foldNumber(Number expr) {
// numbers are "terminal": no more recursive structure to walk
return expr;
}
public Expression foldVariable(Variable expr) {
// another non-recursive expression
return expr;
}
}
class Simplifier extends DefaultFolder {
public Expression foldBinaryOperation(BinaryOperation expr) {
// we want to do a depth-first traversal, ensuring that all
// sub-expressions are simplified before their parents...
// ... so begin by invoking the superclass "default"
// traversal logic.
BinaryOperation folded_expr =
// this cast is safe because we know the default fold
// logic never changes the type of the top-level expression
(BinaryOperation)super.foldBinaryOperation(expr);
// now apply our "shallow" simplification logic on the result
switch (folded_expr.operator) {
case PLUS:
// x + 0 => x
if (folded_expr.right instanceof Number
&& ((Number)(folded_expr.right)).value == 0)
return folded_expr.left;
// 0 + x => x
if (folded_expr.left instanceof Number
&& ((Number)(folded_expr.left)).value == 0)
return folded_expr.right;
break;
case MINUS:
// x - 0 => x
if (folded_expr.right instanceof Number
&& ((Number)(folded_expr.right)).value == 0)
return folded_expr.left;
// 0 - x => -x
if (folded_expr.left instanceof Number
&& ((Number)(folded_expr.left)).value == 0) {
// a weird case: we need to construct a UnaryOperator
// representing -right, then simplify it
UnaryOperation minus_right = new UnaryOperation(
UnaryOperator.NEGATE, folded_expr.right);
return foldUnaryOperation(minus_right);
}
break;
case MUL:
// 1 * x => x
if (folded_expr.left instanceof Number
&& ((Number)(folded_expr.left)).value == 1)
return folded_expr.right;
case DIV:
// x * 1 => x
// x / 1 => x
if (folded_expr.right instanceof Number
&& ((Number)(folded_expr.right)).value == 1)
return folded_expr.left;
break;
}
// no rules applied
return folded_expr;
}
public Expression foldUnaryOperation(UnaryOperation expr) {
// as before, go depth-first:
UnaryOperation folded_expr =
// see note in foldBinaryOperation about safety here
(UnaryOperation)super.foldUnaryOperation(expr);
switch (folded_expr.operator) {
case NEGATE:
// --x => x
if (folded_expr.operand instanceof UnaryOperation
&& ((UnaryOperation)folded_expr).operator ==
UnaryOperator.NEGATE)
return ((UnaryOperation)folded_expr.operand).operand;
// -(number) => -number
if (folded_expr.operand instanceof Number)
return new Number(-((Number)(folded_expr.operand)).value);
break;
}
// no rules applied
return folded_expr;
}
// we don't need to implement the other two; the inherited defaults are fine
}
public class Simplify {
public static void main(String[] args) {
Simplifier simplifier = new Simplifier();
Expression[] exprs = new Expression[] {
new BinaryOperation(
BinaryOperator.PLUS,
new Number(0.0),
new Variable("x")
),
new BinaryOperation(
BinaryOperator.PLUS,
new Number(17.3),
new UnaryOperation(
UnaryOperator.NEGATE,
new UnaryOperation(
UnaryOperator.NEGATE,
new BinaryOperation(
BinaryOperator.DIV,
new Number(0.0),
new Number(1.0)
)
)
)
),
};
for (Expression expr: exprs) {
System.out.println("Unsimplified: " + expr.repr());
Expression simplified = expr.fold(simplifier);
System.out.println("Simplified: " + simplified.repr());
}
}
}
输出:
> java Simplify
Unsimplified: (0.0 + x)
Simplified: x
Unsimplified: (17.3 + --(0.0 / 1.0))
Simplified: 17.3