将算术表达式表示为树

时间:2015-04-05 09:51:48

标签: scala tree functional-programming

为了准备我的考试,我正在做一些scala任务。 任务是在Exp的伴随对象中实现一个函数evaluate,它评估由其参数Exp表示的表达式。该函数必须遵循以下签名:

Exp.evaluate(Exp):Int

完成后,以下代码将打印1:

val e = Sub(Plus(Num(5),
 Mul(Num(9),
 Num(3))),
 Num(5))
println(Exp.evaluate(e))

这就是代码:我被困在这一部分,因为我很困惑如何编写evaluate函数。新的工作版本:

sealed abstract case class Exp
case class Num(n : Int) extends Exp
case class Plus(n1 : Exp, n2 : Exp) extends Exp
case class  Mul(n1 : Exp, n2 : Exp) extends Exp
case class  Sub(n1 : Exp, n2 : Exp) extends Exp

object Exp {
  def evaluate(e : Exp) : Int = {
    e match {
      case Num(n) => n
      case Plus(n1, n2) => add(n1, n2)
      case Mul(n1, n2) => times(n1, n2)
      case Sub(n1, n2) => minus(n1, n2)
      //case _ => error("nothing")
    }
  }

  def add(n1 : Exp, n2 : Exp) : Int = (n1,n2) match {
    case (Num(x), Num(y)) => x+y
  }

  def times(n1 : Exp, n2 : Exp) : Int = (n1,n2) match {
    case (Num(x), Num(y)) => x*y
  }

  def minus(n1 : Exp, n2 : Exp) : Int = (n1,n2) match {
    case (Num(x), Num(y)) => x-y
  }
}
//

但现在它没有通过我的测试:

    def testEvalSkel {
    expect(11) {
      evaluate(Plus(Mul(Num(3),Num(4)),Sub(Num(3),Num(4))))
    }
  }

我收到此错误:

Test testEvalSkel failed: (Mul(Num(3),Num(4)),Sub(Num(3),Num(4))) (of class scala.Tuple2)

1 个答案:

答案 0 :(得分:2)

尝试这种方法可行。

trait Exp

  case class Num(n: Int) extends Exp

  case class Plus(n1: Exp, n2: Exp) extends Exp

  case class Mul(n1: Exp, n2: Exp) extends Exp

  case class Sub(n1: Exp, n2: Exp) extends Exp

  object Exp {
    def evaluate(e: Exp): Int = {
      e match {
        case Num(n) => n
        case Plus(e1, e2) => add(e1,e2)
        case Mul(e1, e2) => times(e1, e2)
        case Sub(e1, e2) => minus(e1, e2)
      }
    }

    def add(n1: Exp, n2: Exp): Int = evaluate(n1) + evaluate(n2)

    def times(n1: Exp, n2: Exp): Int = evaluate(n1) *  evaluate(n2)

    def minus(n1: Exp, n2: Exp): Int = evaluate(n1) - evaluate(n2)
  }

  val e = Plus(Mul(Num(3),Num(4)),Sub(Num(3),Num(4)))
  println(Exp.evaluate(e)) // prints 11