scala - 如何将该组列表的功能重新制作为简单递归?
问题描述
我编写了按索引对列表元素进行分组的函数,第一个列表中的索引为奇数,甚至在第二个中。但我不知道如何通过简单的递归来实现它并且不会出现类型不匹配。
这是代码:
// 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))
解决方案
您必须调用下一个递归,解包结果元组,将每个头元素预先附加到正确的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)
}
推荐阅读
- arrays - 索引超出范围 Alamofire Swift 的外部功能
- r - 突出显示前 3 个值
- python - 在python中合并两个数据框时获取空数据框
- reactjs - 用于 Flask 和 React 的 Azure 发布管道
- oracle - 插入触发器 Oracle 之后 - 如何确保仅插入唯一记录?
- asp.net - 为什么 Asp.Net SignalR 使用相同的 ConnectionId 在集线器中多次调用 OnDisconnect?
- swift - 不同设备的 UIScrollview 约束
- javascript - 使用 React Hooks Helper 设置多步表单的状态(链接到代码框)
- python - 将机器学习模型与烧瓶网站集成时出错
- r - 根据条件选择值