小编lea*_*020的帖子

Scala 递归/尾递归

我正在尝试使用 Scala 练习递归和尾递归函数,我创建了一个尾递归函数来对两个列表中的值求和。我也尝试对递归执行相同的操作,但我能想到的唯一方法是每次调用方法时修改参数,如尾递归。你能帮我吗?

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]  = {

}
Run Code Online (Sandbox Code Playgroud)

recursion scala

0
推荐指数
1
解决办法
61
查看次数

标签 统计

recursion ×1

scala ×1