首页 > 解决方案 > 如何将该组列表的功能重新制作为简单递归?

问题描述

我编写了按索引对列表元素进行分组的函数,第一个列表中的索引为奇数,甚至在第二个中。但我不知道如何通过简单的递归来实现它并且不会出现类型不匹配。

这是代码:

// Simple recursion
def group1(list: List[Int]): (List[Int], List[Int]) = list match {
  case Nil => (Nil, Nil)
  case head :: Nil => (List(head), Nil)
  case head :: tail => // how can I make this case?
}

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

// Tail recursion
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 head :: Nil => ((head :: listA).reverse, listB.reverse)
    case head :: headNext :: tail => group2Helper(tail, head :: listA, headNext :: listB)
  }
  group2Helper(list, Nil, Nil)
}

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

标签: scalafunctionfunctional-programming

解决方案


您必须调用下一个递归,解包结果元组,将每个头元素预先附加到正确的List,然后重新打包新的结果元组。

def group1(list: List[Int]) :(List[Int], List[Int]) = list match {
  case Nil                => (Nil, Nil)
  case head :: Nil        => (List(head), Nil)
  case hdA :: hdB :: tail => val (lstA, lstB) = group1(tail)
                             (hdA :: lstA, hdB :: lstB)
}

推荐阅读