abstract class Tree
case class Sum(l: Tree, r: Tree) extends Tree
case class Val(n: String) extends Tree
case class Const(v: Int) extends Tree
type Environment = String => Int
def eval(t: Tree, env: Environment):Int = t match {
case Sum(l, r) => eval(l, env) + eval(r, env)
case Val(n) => env(n)
case Const(v) => v
}
val exp = Sum(Val("x"), Sum(Val("y"), Const(4)))
println("x + (y + 4) = " + eval(exp, {case "x" => 1 case "y" => 2}))
calc.scala
Timer.scala
参考: