Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala,调用列表并对代码进行简单测试_Scala - Fatal编程技术网

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

Scala,调用列表并对代码进行简单测试,scala,Scala,这是求和函数的代码(需要检查) 如何用列表检查它?它通常是如何简单地完成的,以及如何在此基础上编写简单的断言?要检查您的方法,请在主方法中调用它: 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))) } } 对列表

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


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

要检查您的方法,请在主方法中调用它:

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)))
  }
}
对列表调用求和操作的另一种方法是:

List(1,2,3).sum

首先,scala中有一个内置的求和函数:

> 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中有一个工具可以简化测试数据的生成,如下所示:。它将为您的函数提供各种输入:大的和负数、零、null、空字符串、空列表、大列表——所有这些都是一般开发人员忘记检查的。这对新手来说并不容易,但绝对值得一看。

您似乎正在学习Coursera课程。这是一个示例作业,向您介绍未来作业的流程。有一个视频可以指导您完成整个过程,包括使用交互式sbt控制台测试代码。您还下载了一个文档非常丰富的示例测试套件,其中包含对求和函数的一些基本检查,并将指导您完成编写其他测试用例的过程。谢谢Carsten,我仍然对语法感到非常困惑,希望随着时间的推移,它会变得更流畅。谢谢,我会再检查的。我个人认为这是一个很好的问题,没有坏问题。Enlightthis在“Scala工作表”中工作得非常好。我试图在.Scala中实时运行它,但不理解其中的区别。嗯,工作表通常用于处理现有代码或新代码的原型——在大量代码中,我们不能也不应该将所有内容都加载到其中。工作表。或者你在问别的事情?
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)
}