我正在写课程分配,问题是要计算表达式的值。我提供了下面的代码。在computeValues方法中,我将NotInferredB1作为预期的数据类型。
以下代码:
sealed abstract class Expr
final case class Literal(v: Double) extends Expr
final case class Ref(name: String) extends Expr
final case class Plus(a: Expr, b: Expr) extends Expr
final case class Minus(a: Expr, b: Expr) extends Expr
final case class Times(a: Expr, b: Expr) extends Expr
final case class Divide(a: Expr, b: Expr) extends Expr
def getReferenceExpr(name: String,
references: Map[String, Expr]) = {
references.get(name).fold[Expr] {
Literal(Double.NaN)
} {
exprSignal =>
exprSignal
}
}
def eval(expr: Expr, references: Map[String, Expr]): Double = {
expr match {
case Literal(a)=> a
case Plus(a, b) => eval(a, references) + eval(b, references)
case Minus(a,b) => eval(a, references) - eval(b, references)
case Times(a,b) => eval(a, references) * eval(b, references)
case Divide(a,b) => eval(a, references) / eval(b, references)
case Ref(name) => eval(getReferenceExpr(name, references), references - name)
}
}
import scala.collection.Map
var namedExpressions: Map[String, Expr] = Map("a" -> Plus(Literal(2) ,Literal(3)), "b" -> Times(Ref("a"),Literal(2)))
def computeValues(namedExpressions: Map[String, Expr]):Map[String, Double] = {
var values1 = Map[String,Double]()
namedExpressions foreach {
case (key,val1) => {
values1 += Map(key -> eval(val1,namedExpressions))
}
values1
}
}
谢谢。
答案 0 :(得分:0)
以下更改有效:
def computeValues(namedExpressions: Map[String, Expr]):Map[String, Double] = {
var values1 = Map[String,Double]()
namedExpressions foreach {
case (key,val1) => {
values1 += (key -> eval(val1,namedExpressions))
}
}
values1
}