我正在嘗試使用 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] = {
}
uj5u.com熱心網友回復:
模式匹配。這是蜜蜂的膝蓋。
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}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/356396.html
下一篇:圣誕樹的錯誤顯示
