我想到的简化是
0*e = e*0 = 0
1*e = e*1 = 0+e = e+0 = e-0 = e
并简化常量子表达式,例如: Plus (Const 1) (Const 2)
将成为Const 3
。我不希望连接变量(或变量和常量):Var "st"
是与Var "s"
不同的变量。
例如simplify(Plus (Var "x") (Const 0))= Var "x"
答案 0 :(得分:2)
那么,你不能对个别情况应用模式匹配吗?
simplify (Plus (Const 0) (Expr x)) = simplify (Expr x)
simplify (Plus (Expr x) (Const 0)) = simplify (Expr x)
simplify (Mult (Const 0) _) = Const 0
simplify (Mult _ (Const 0)) = Const 0
– … and so on
编辑:是的,当然......已经添加了递归。
答案 1 :(得分:0)
我对haskell了解不多,但基本上你会想要进行表达式遍历。
树是 EXP :(运算符)(EXP)(EXP) EXP:(const) EXP:(var) 然后你的简化就变成了 继承了伪代码simplify(Exp e)
if (e is const) return e
else if (e is var) return e
else
{//encode simplification rules
Exp left = simplify(e.left)
Exp right = simplify(e.right)
if(operator is PLUS)
{
if(left == 0) return right;
if(right == 0) return left;
}
else if(operator is MULT)
{
if(left == 1) return right;
if(right == 1) return left;
if(left == 0) return 0;
if(right == 0) return 0;
}
//and so on for other operators
}
这是一种java esque,但我认为这个想法存在,基本上你将不得不进行树遍历。