在地图中找不到密钥

时间:2012-11-26 20:02:54

标签: scala map

鉴于这个非常简单的变量 - 子句模型

class Variable(name: String, negated: Boolean = false) {
    def evaluate(b: Boolean): Boolean = negated match {
        case false => b
        case true => !b
    }

    def negate = new Variable(this.name, !this.negated)

    override def toString = negated match {
        case false => name
        case true => "~" + name
    }

    override def hashCode() = name.hashCode()

    override def equals(obj: Any) = name.equals(obj)
}

class Clause(vars: List[Variable]) {
    def evaluate(values: Map[Variable, Boolean]): Boolean = {
        val evaluatedVars = vars.map(v => v.evaluate(values(v)))
        (false /: evaluatedVars)(_ || _)
    }
}

这个简单的断言会引发异常

val c = new Variable("c")
val d = new Variable("d")
val c3 = new Clause(List(c.negate, d))
assertTrue( c2.evaluate( Map(c -> false, d -> true) ) )
  

java.util.NoSuchElementException:找不到密钥:~c

我错过了什么?

1 个答案:

答案 0 :(得分:6)

Variable不是String。您的equals已损坏。

你想:

override def equals(a: Any) = a match {
  case v: Variable => v == name
  case s: String => name == s
  case _ => false
}

(如果您不想私下公开name,但希望Variable匹配随机字符串。)