Scala-预期的(String,NotInferedB1)实际的(String,Double)

时间:2018-07-14 21:24:27

标签: scala

我正在写课程分配,问题是要计算表达式的值。我提供了下面的代码。在computeValues方法中,我将NotInferredB1作为预期的数据类型。

  1. 有人可以解释什么是NotInferred数据类型吗?
  2. 您还可以解释一下为什么它会期望NotInferred吗,因为不知道values1被声明为(String,Double)。

以下代码:

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
    }
  }

谢谢。

1 个答案:

答案 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
  }