传递空List参数是调用IndexOutOfBoundsException

时间:2013-01-31 01:27:11

标签: scala

我正在尝试使用合并排序在Scala中进行反转计数而无法取得进展,因为其中一个方法是抛出IndexOutOfBoundsException以将空List作为参数传递。

def sortAndCountInv(il: List[Int]): Int = {

def mergeAndCountInv(ll: List[Int], rl: List[Int]): (List[Int], Int) = {
  println("mergeAndCountInv : ")
  if (ll.isEmpty && !rl.isEmpty) (rl, 0)
  if (rl.isEmpty && !ll.isEmpty) (ll, 0)
  if (ll.isEmpty && rl.isEmpty) (List(), 0)
  if (ll(0) <= rl(0)) {

    val x = mergeAndCountInv(ll.tail, rl)//*passing empty list, ll.tail invoking IndexOutOfBoundsException*//


    (ll(0) :: x._1, x._2)
  } else {
    val y = mergeAndCountInv(ll, rl.tail)
    (rl(0) :: y._1, 1 + y._2)
  }
}

def sortAndCountInv(l: List[Int], n: Int): (List[Int], Int) = {
  if (n <= 1) (l, 0)
  else {
    val two_lists = l.splitAt(n / 2)
    val x = sortAndCountInv(two_lists._1, n / 2)
    val y = sortAndCountInv(two_lists._2, n / 2)
    val z = mergeAndCountInv(x._1, y._1)
    (z._1, x._2 + y._2 + z._2)
  }
}

val r = sortAndCountInv(il, il.length)
println(r._1.take(100))
r._2

}

2 个答案:

答案 0 :(得分:2)

通常使用模式匹配来更清楚地表达这种事情:

  def mergeAndCountInv(ll: List[Int], rl: List[Int]): (List[Int], Int) =
    (ll, rl) match {
      case (Nil, Nil) => (Nil, 0)

      case (Nil, _)   => (rl, 0)

      case (_, Nil)   => (ll, 0)

      case (ll0 :: moreL, rl0 :: moreR) =>
        if (ll0 <= rl0) {
          val x = mergeAndCountInv(moreL, rl)
          (ll0 :: x._1, x._2)
        }
        else {
          val y = mergeAndCountInv(ll, moreR)
          (rl0 :: y._1, 1 + y._2)
        }
    }

答案 1 :(得分:1)

当您检查左侧或右侧或两个列表是否为空时,我建议您在else中使用mergeAndCountInv。因为不是返回而是忽略计算中的元组。