递归函数抛出 StackOverflowError

Recursive function throw StackOverflowError

我在使用此功能时遇到问题。我需要处理超过 100 万条记录,但这会崩溃。看起来只适用于数千条记录,并为更大的列表抛出 WhosebugError。有什么建议吗?

def split(list: List[(Pair, Boolean)]): List[List[Pair]] = list match {
  case Nil => Nil
  case head :: tail => {
    val (l1, l2) = tail.span(!_._2)
    (head :: l1).map(_._1) :: split(l2)
  }
}

您的程序将抛出 Whosebug 异常:

Exception in thread "main" java.lang.WhosebugError
    at scala.collection.immutable.List.map(List.scala:283)

原因很简单因为你的方法不是尾递归的 如果你用@tailrec 注释它,它不会编译:

  @tailrec
  def split(list: List[(Pair, Boolean)]): List[List[Pair]] = list match {
    case Nil => Nil
    case head :: tail => {
      val (l1, l2) = tail.span(!_._2)
      (head :: l1).map(_._1) :: split(l2)
    }
  }

解决办法是让你的回避成为尾部记录,或者改用某种循环

您可以尝试这样的操作:

 @tailrec
  def split(list: List[(Pair, Boolean)], accumulator:  List[List[Pair]] = List[List[Pair]]()): List[List[Pair]] = list match {
    case Nil => accumulator
    case head :: tail => {
      val (l1, l2) = tail.span(!_._2)
      split(l2, (head :: l1).map(_._1)::accumulator)
    }
  }