这是 sum 函数的代码(需要检查)
object Lists {
def sum(xs: List[Int]): Int =
[some scala code]
}
怎么可能用列表来检查呢?它通常如何简单地完成,以及如何在此编写简单的断言?
这是 sum 函数的代码(需要检查)
object Lists {
def sum(xs: List[Int]): Int =
[some scala code]
}
怎么可能用列表来检查呢?它通常如何简单地完成,以及如何在此编写简单的断言?
检查您的方法在主要方法中调用它:
object Lists {
def sum(xs: List[Int]): Int =
if(xs.isEmpty) 0
else xs.head + sum(xs.tail)
def main(args: Array[String]) {
println(sum(List(1,2,3)))
}
}
在列表上调用 sum 操作的另一种方法是:
List(1,2,3).sum
首先在 scala 中有一个内置的 sum 函数:
> List(1,2,3,4).sum
res0: Int = 10
所以你可以假设它工作得很好,并针对它断言你的功能。接下来,我将通过极端情况测试您的代码。
等等
object Lists {
// I'm writing checks inline, but commonly we write them in separate file
// as scalatest or specs test
// moreover, require, which is build in scala function, is mostly used for checking of input
// but I use it there for simplicity
private val Empty = List.empty[Int]
private val Negatives = List(-1, 1, -2, 2, 3)
private val TenZeroes = List.fill(10)(0)
require(sum(Empty) == Empty.sum)
require(sum(Negatives) == Negatives.sum)
require(sum(TenZeroes) == 0)
// etc
def sum(xs: List[Int]): Int =
if(xs.isEmpty) 0
else xs.head + sum(xs.tail)
}
scala 中有一个工具可以简化像这样的测试数据的生成:scalacheck。它将为您的函数提供各种输入:大数和负数、零、空值、空字符串、空列表、大列表——普通开发人员忘记检查的所有内容。这对新手来说并不容易,但绝对值得一看。