我正在课程中学习Functional Programming Principles in Scala课程。有一个Peano numbers的实现示例,如下所示:
abstract class Nat {
def isZero: Boolean
def predecessor: Nat
def successor: Nat = new Succ(this)
def +(that: Nat): Nat
def -(that: Nat): Nat
}
object Zero extends Nat {
def isZero = true
def predecessor: Nat = throw new Error("0.predecessor")
def +(that: Nat): Nat = that
def -(that: Nat): Nat = if (that.isZero) this else throw new Error("negative number")
}
class Succ(n: Nat) extends Nat {
def isZero: Boolean = false
def predecessor: Nat = n
def +(that: Nat): Nat = new Succ(n + that)
def -(that: Nat): Nat = if (that.isZero) this else n - that.predecessor
}
我写了几个单元测试。大多数传递,但以下 - 以天真方式编写 - 都是由于明显的原因(不同实例的比较)而失败:
trait Fixture {
val one = new Succ(Zero)
val two = new Succ(one)
}
test("successor of zero is one") {
new Fixture {
assert(Zero.successor == one)
}
}
test("successor of one is two") {
new Fixture {
assert(one.successor == two)
}
}
test("one plus zero is one") {
new Fixture {
assert((one + Zero) === one)
}
}
test("one plus one is two") {
new Fixture {
assert((one + one) === two)
}
}
我的问题是:如何实施单元测试以成功测试+和 - 对peano数字的操作?
以防万一,您可以在这里找到remaining unit tests。
答案 0 :(得分:1)
感谢来自Cyrille Corpet的提示,我认为使用case class
是优雅的&#34;按结构进行比较,而不是通过引用进行比较&#34; < / em>的。所有单元测试现在都没有任何变化。
case class Succ(n: Nat) extends Nat {
def isZero: Boolean = false
def predecessor: Nat = n
def +(that: Nat): Nat = new Succ(n + that)
def -(that: Nat): Nat = if (that.isZero) this else n - that.predecessor
}
答案 1 :(得分:-1)
看看你的测试看起来你想测试相等条件,你应该写一个函数:
def eq(i: Nat, j: Nat): Boolean =
if (i.isZero | j.isZero)
i.isZero == j.isZero
else
eq(i.predecessor, j.predecessor)
替换您的===
&amp; ==
致电eq
。您也可以考虑重写等于方法,而不是将其作为外部(测试)函数。