Scala,调用列表并对代码进行简单测试

时间:2013-09-24 10:51:33

标签: scala

这是sum函数的代码(需要检查)

object Lists { 

 def sum(xs: List[Int]): Int = 

    [some scala code]

}

如何用列表检查它?它通常是如何简单地完成的,以及如何在此基础上编写简单的断言?

2 个答案:

答案 0 :(得分:2)

检查你的方法在main方法中调用它:

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

答案 1 :(得分:2)

首先,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。它将为您的函数提供各种输入:大数字和负数,零,空值,空字符串,空列表,大型列表 - 平均开发人员忘记检查的所有内容。这对新手来说并不容易,但绝对值得一看。