首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Scala递归/尾递归

Scala递归/尾递归
EN

Stack Overflow用户
提问于 2021-11-11 01:30:05
回答 1查看 49关注 0票数 0

我正在尝试使用Scala来练习递归和尾递归函数,我已经创建了一个尾递归函数来对两个列表中的值求和。我也试图对递归做同样的事情,但我能想到的唯一方法就是在每次调用方法时修改参数,就像尾递归一样。你能帮帮我吗?

代码语言:javascript
运行
复制
def callTailRecursive(list1 : List[Int], list2 : List[Int]) : List[Int] = {
  def callHelper(list1 : List[Int], list2 : List[Int], outputList : List[Int]): List[Int] ={
    if(!list1.isEmpty && !list2.isEmpty){
      callHelper(list1.tail,list2.tail,outputList:+(list1.head + list2.head))
    }else if(list1.isEmpty && !list2.isEmpty){
      callHelper(list1,list2.tail,outputList:+(list2.head))
    }else if(!list1.isEmpty && list2.isEmpty){
      callHelper(list1.tail,list2,outputList:+(list1.head))
    }else{
      outputList
    }
  }
  callHelper(list1,list2,List())
}

def callRecursive(n : Int, list1 : List[Int], list2 : List[Int], outputList : List[Int]): List[Int]  = {

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-11 02:02:56

模式匹配。这是蜜蜂的膝盖。

代码语言:javascript
运行
复制
def callRecursive(list1: List[Int], list2: List[Int]): List[Int] = (list1,list2) match {
  case (hd1::tl1, hd2::tl2) => (hd1+hd2) :: callRecursive(tl1, tl2)
  case (_, Nil) => list1
  case (Nil, _) => list2
}

def notRecursive(list1: List[Int], list2: List[Int]): List[Int] =
  list1.zipAll(list2, 0, 0).map{case (a,b) => a+b}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69922195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档