下面是我试图用来说明模式匹配的代码:
package patternmatching
object patterntest {
abstract class Expr
case class Var(name: String) extends Expr
case class Number(num: Double) extends Expr
case class UnOp(operator: String , arg: Expr) extends Expr
case class BinOp(operator: String, left: Expr, right: Expr) extends Expr
def simplifyTop(expr: Expr): Expr = expr match {
case UnOp("-", UnOp("-", e)) => e //double negation
case BinOp("+", e, Number(0)) => e //adding zero
case BinOp("*", e, Number(1)) => e //Mutiplying by one
case _ => expr
}
def main(args: Array[String]) {
UnOp("-" , UnOp("-", e))
}
}
如何测试每个模式?主方法中的 UnOp("-" , UnOp("-", e)) 行给出了一个错误:
not found: value e