简化Scala中的简单表达式

时间:2014-10-14 16:39:20

标签: scala symbolic-math

我正在学习scala并尝试创建一种方法,通过应用简单的心律失常规则来简化简单表达。然而,它似乎并没有改变我喜欢的方式,或根本不改变这个问题。当我打印出来时,简化并没有显示出来。我将不胜感激任何帮助/建议,谢谢!     我用来测试的打印语句在下面跟着输出。

println("Expression: " + exp)
println("Simplified: " + simplify(exp))

输出:

表达式:((1 * x)+(0 + y))< - 这是正确的

简化:((1 * x)+(0 + y))< - 这不是我所期望的。我期待像((x)+(y))

这样的东西

我的代码如下:

    lazy val exp: Tree = Sum(Times(Const(1), Var("x")), Sum(Const(0), Var("y")))

    abstract class Tree
    case class Sum(l: Tree, r: Tree) extends Tree {
      override def toString = "(" + l + "+" + r + ")"
    }
    case class Minus(l: Tree, r: Tree) extends Tree {
      override def toString = "(" + l + "-" + r + ")"
    }
    case class Times(l: Tree, r: Tree) extends Tree {
      override def toString = "(" + l + "*" + r + ")"
    }
    case class Divide(l: Tree, r: Tree) extends Tree {
      override def toString = "(" + l + "/" + r + ")"
    }
    case class Var(n: String) extends Tree {
      override def toString = n
    }
    case class Const(v: Int) extends Tree {
      override def toString = v.toString
    }

    def simplify(t: Tree): Tree = t match {
      case Times(Const(1), r)     => simplify(r)
      case Times(l, Const(1))     => simplify(l)
      case Times(Const(0), r)     => Const(0)
      case Times(l, Const(0))     => Const(0)
      case Sum(Const(0), r)       => simplify(r)
      case Sum(l, Const(0))       => simplify(l)
      case Minus(l, Const(0))     => simplify(l)
      case Minus(l, r) if l == r  => Const(0)
      case Divide(Const(0), r)    => Const(0)
      case Divide(l, Const(1))    => simplify(l)
      case Divide(l, r) if l == r => Const(1)
      case _                      => t
    }

1 个答案:

答案 0 :(得分:4)

你没有处理这些案件:

case Times(l, r) => Times(simplify(l), simplify(r))
case Sum(l, r) => Sum(simplify(l), simplify(r))
case Minus(l, r) => Minus(simplify(l), simplify(r))
case Divide(l, r) => Divide(simplify(l), simplify(r))

此外,您可能希望编写一个不断简化的包装器,直到它不再被简化为止(即直到simplify(x) == x)。