为什么Scala'匹配'陷入永久循环

时间:2016-01-25 21:28:09

标签: scala loops testing recursion

我正在尝试查找Scala中列表中的数字是否在降序。当我运行我的测试用例时,控制台会打印一个任意列表并且永远不会完成,这让我觉得它陷入了永久的循环。

函数isDescending必须将列表作为参数,并且必须返回布尔值。我们必须使用递归,不能使用集合包中的函数。

代码:

  def isDescending(lst: List[Int]): Boolean ={
    isDescendingHelper(lst, 0, true)
  }

  def isDescendingHelper(lst: List[Int], prev: Int, begin: Boolean): Boolean = {
    lst match{
      case Nil =>  true
      case head :: tail => {
        if (begin){
          isDescendingHelper(lst, head, false)
        } else if (head <= prev){
          isDescendingHelper(lst, head, false)
        } else {
          false
        }
      }
    }
  }

测试案例:

  test("isDescending test case"){
    assert(isDescending(List()))
    assert(isDescending(List(0, 0, 0)))
    assert(isDescending(List(3, 6, 8)))
    assert(isDescending(List(3, 6, 8 , 7)) == false)
    assert(isDescending(List(0)))
  }

1 个答案:

答案 0 :(得分:3)

你总是匹配同一个列表lst,这样做列表永远不会用尽,你想要传递尾巴:

def isDescendingHelper(lst: List[Int], prev: Int, begin: Boolean): Boolean = {
  lst match{
    case Nil =>  true
    case head :: tail => {
      if (begin){
       isDescendingHelper(tail, head, false)
      } else if (head <= prev){
        isDescendingHelper(tail, head, false)
      } else {
        false
      }
    }
  }
}