1

我想编写一个使用分布规则简化这个数学表达式的scala程序:

a*b+a*c = a(b+c)

为了解决这个例子,我快速编写了以下代码:

object Test {

  sealed abstract class Expr

  case class Var(name: String) extends Expr

  case class BinOp(operator: String, left: Expr, right: Expr) extends Expr


  def main(args: Array[String]) {
    val expr = BinOp("+", BinOp("*", Var("a"), Var("b")), BinOp("*", Var("a"), Var("c")))
    println(simplify(expr)) //outputs "a(b + c)"
  }

  def simplify(expr: Expr) : String = expr match {
    case BinOp("+", BinOp("*", Var(x), Var(a)), BinOp("*", Var(y), Var(b))) if (x == y) => "" + x + "*(" + a + " + " + b + ")"
    case _ => "" //no matter for the test since I test the first case statically
  }

}

有没有更好的方法来实现这一目标?

在不为每个组合重复案例的情况下管理操作数顺序的最佳方法是什么(会很难看......)?确实,这些表达式呢:

a*b+a*c = a(b+c)

a*b+c*a = a(b+c)

b*a+a*c = a(b+c)

b*a+c*a = a(b+c)

4

1 回答 1

1

如果Expr保持交换律,它必须是

def simplify(expr: Expr) : String = expr match {
  case expr @ BinOp("+", BinOp("*", Var(x), Var(a)), BinOp("*", Var(y), Var(b))) => {
    def another(that: String) = {
      Seq((x, a), (a, x)) find (_._1 == that) map (_._2)
    }

    val byY = another(y).map(z => BinOp("+", Var(y), BinOp("*", Var(z), Var(b)))) // combine by y
    val byB = another(b).map(z => BinOp("+", Var(b), BinOp("*", Var(z), Var(y)))) // combine by b
    (byY orElse byB getOrElse expr).toString
  }
  case _ => "" //no matter for the test since I test the first case statically
}

byYbyB具有相同的结构。这不是最好的,您可能会重用一些代码。:P

于 2012-12-20T11:28:30.120 回答