鉴于这个非常简单的变量 - 子句模型
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
我错过了什么?
答案 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
匹配随机字符串。)