我是Scala的新手,我正在关注本教程http://docs.scala-lang.org/tutorials/scala-for-java-programmers.html,其中有一个案例类使用示例。
我试图执行以下示例:
package classes
abstract class Tree
case class Sum(l: Tree, r: Tree) extends Tree
case class Var(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 Var(n) => env(n)
case Const(v) => v
}
}
但问题是我无法执行它并且我怀疑原因是我无法在那里添加main方法,因为它是一个类而不是一个对象。所以我在那里用main方法创建了一个对象:
package classes
object TreeOperations {
type Environment = String => Int //XXX: cannot I import it somehow?
def main(args: Array[String]) {
// evaluating (x+x)+(7+y) expression
val exp: Tree = Sum(Sum(Var("x"), Var("x")),Sum(Const(7), Var("y")))
val env: Environment = { case "x" => 5 case "y" => 7} // x := 5, y := 7
println("Expression: " + exp)
println("Evaluation with x=5, y=7: " + eval(exp, env)) //XXX no eval here
}
}
但后来我发现了两件事:
我无法访问类型Environment,因为它是一个不同的类(我尝试过Tree.Environment但它不起作用)。
我也无法访问eval(...)(我也试过了)。
所以我想知道解决这些困难的最佳方法是什么。
提前致谢!
答案 0 :(得分:2)
在本教程中,我没有看到他们在eval
案例类中定义类型声明和Const
方法的地方。我会将这些放在case类之外但是在同一个对象或你导入的对象中,如下所示:
将所有定义放在一个或多个文件中(在这种情况下,只需确保在需要时导入声明):
package classes
abstract class Tree
case class Sum(l: Tree, r: Tree) extends Tree
case class Var(n: String) extends Tree
case class Const(v: Int) extends Tree
在TreeOperations文件中,您将拥有以下内容:
package classes
import Tree._
object TreeOperations {
type Environment = String => Int //XXX: cannot I import it somehow?
def eval(t: Tree, env: Environment): Int = t match {
case Sum(l, r) => eval(l, env) + eval(r, env)
case Var(n) => env(n)
case Const(v) => v
}
def main(args: Array[String]) {
// evaluating (x+x)+(7+y) expression
val exp: Tree = Sum(Sum(Var("x"), Var("x")),Sum(Const(7), Var("y")))
val env: Environment = { case "x" => 5 case "y" => 7} // x := 5, y := 7
println("Expression: " + exp)
println("Evaluation with x=5, y=7: " + eval(exp, env)) //XXX no eval here
}
}
答案 1 :(得分:-1)
我会这样写:
package classes
abstract class Tree
case class Sum(l: Tree, r: Tree) extends Tree
case class Var(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 Var(n) => env(n)
case Const(v) => v
}
}
object AppMain extends App {
// evaluating (x+x)+(7+y) expression
val exp: Tree = Sum(Sum(Var("x"), Var("x")),Sum(Const(7), Var("y")))
val env: Environment = { case "x" => 5 case "y" => 7} // x := 5, y := 7
println("Expression: " + exp)
println("Evaluation with x=5, y=7: " + eval(exp, env)) //XXX no eval here
}