English 中文(简体)
如何使用原始递归简化下面的表达式?[重复]
原标题:
  • 时间:2008-11-27 18:24:21
  •  标签:
This question already has answers here:
Closed 10 years ago.

Possible Duplicate:
Symbolic simplification in Haskell (using recursion?)

我心中所想的简化是:

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"的中文翻译为:简化(加(变量“x”)(常量0))= 变量“x”

问题回答

嗯,你不能将模式匹配应用于各个情况吗?

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

编辑:当然可以…添加了递归。

我不太了解 Haskell,但基本上你需要进行表达式树遍历。

the tree is EXP: (operator) (EXP) (EXP) EXP: (const) EXP: (var)

then your simplify becomes heres the psuedo code

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 但我认为这个想法在这里了,本质上你将不得不进行树遍历。





相关问题
热门标签