简体   繁体   中英

How fix type mismatch using tail recursion?

I need to group one list into two by index numbers, if it odd to first list, if even to second.

Here is my function

def group2(list: List[Int]): (List[Int], List[Int]) = {
  def group2Helper(list: List[Int], listA: List[Int], listB: List[Int]): (List[Int], List[Int]) = list match {
    case Nil => (listA, listB)
    case head :: tail => group2Helper(tail.tail, listA ::: List(head), listB ::: List(tail.head))
 }
}

group2(List(2, 6, 7, 9, 0, 4, 1))

As result it have to return (List(2, 7, 0, 1), List(6, 9, 4))

Now I have problem: "Type mismatch, found: Unit, required: (List[Int], List[Int])", that highlighted at last brace

group2 defines a function, but doesn't actually execute it. After you define group2helper , make sure you call it and you should be fine.

After you fix the missing group2helper() invocation your code still won't work because you're processing the input two at a time, but the input List has an odd number of elements so that will cause a runtime error.

A different approach is to process the input one at a time and keep swapping which list gets added to.

def group2(list: List[Int]): (List[Int], List[Int]) = {
  def group2Helper(list: List[Int], listA: List[Int], listB: List[Int]): (List[Int], List[Int]) = list match {
    case Nil => (listA.reverse, listB.reverse)
    case hd :: tl => group2Helper(tl, listB, hd :: listA)
  }
  group2Helper(list, Nil, Nil)
}

group2(List(2, 6, 7, 9, 0, 4, 1))
//res0: (List[Int], List[Int]) = (List(6, 9, 4),List(2, 7, 0, 1))

Two things worth noting: 1) When building a List it is often more efficient to pre-pend (ie build it backwards) and then reverse the result, and 2) the order of the output lists will depend on whether the input has an even or odd number of elements, but the content of each output List will be correct.


OK, so there's a simple fix for the order-of-output-lists problem.

def group2(list: List[Int]): (List[Int], List[Int]) = {
  def group2Helper(list: List[Int], listA: List[Int], listB: List[Int]): (List[Int], List[Int]) = list match {
    case Nil          => (listA.reverse, listB.reverse)
    case hd :: Nil    => ((hd::listA).reverse, listB.reverse)
    case a :: b :: tl => group2Helper(tl, a::listA, b::listB)
  }
  group2Helper(list, Nil, Nil)
}

This is a return to the original two-at-a-time processing, but with two different termination patterns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM