为什么Scala返回';'预期但','发现错误?

时间:2018-12-10 22:43:04

标签: scala

我目前正在尝试使用一种有效的合并排序算法在Scala中编写一个反转计数算法。

合并排序功能按预期运行,但是当我尝试将计数添加为参数之一时,我得到了错误:

Error:(14, 29) ';' expected but ',' found.
      case (_, Nil) => left, count
                           ^

这是程序:

object MergeSort {

  def mergeSort(inputList: List[Int]): List[Int] = {

    if (inputList.length <= 1) inputList

    else {
      val (left, right) = inputList.splitAt(inputList.size / 2)
      merge(mergeSort(left), mergeSort(right), 0)
    }

  }

  def merge(left: List[Int], right: List[Int], count: Int): List[Int] =
    (left, right) match {
      case (_, Nil) => left, count
      case (Nil, _) => right, count
      case (leftHead :: leftTail, rightHead :: rightTail) =>
        if (leftHead < rightHead){
          val (leftList, leftCount) = leftHead :: merge(leftTail, right, count)
          return (leftList, leftCount)
        }
        else {
          val (rightList, rightCount) = rightHead :: merge(left, rightTail, count)
          val mergeInversions = leftCount + left.length
          return (rightList, mergeInversions)
        }
    }

  val inputList: List[Int] = List(10, 3, 5, 1, 7, 6)

  val sorted_arr = mergeSort(inputList)

}

1 个答案:

答案 0 :(得分:0)

  

@ sepp2k在注释中正确指出,如果要创建元组,则需要将其包装在括号内。

这是可行的解决方案:

object MergeSort {

  def mergeSort(inputList: List[Int]): List[Int] = {

    if (inputList.length <= 1) inputList
    else {
      val (left, right) = inputList.splitAt(inputList.size / 2)
      merge(mergeSort(left), mergeSort(right), 0)._1
    }

  }

  def merge(left: List[Int], right: List[Int], count: Int): (List[Int], Int) =
    (left, right) match {
      case (_, Nil) => (left, count)
      case (Nil, _) => (right, count)
      case (leftHead :: leftTail, rightHead :: rightTail) =>
        if (leftHead < rightHead) {
          val left = merge(leftTail, right, count)
          val (leftList, leftCount) = (leftHead :: left._1, left._2)
          (leftList, leftCount)
        } else {
          val right = merge(left, rightTail, count)
          val (rightList, rightCount) = (rightHead :: right._1, right._2)
          val mergeInversions = rightCount + left.length
          (rightList, mergeInversions)
        }
    }

  val inputList: List[Int] = List(10, 3, 5, 1, 7, 6, 0)

  val sorted_arr = mergeSort(inputList)
}