2017-10-06 99 views
0

这可能是一个奇怪的问题,但...斯卡拉尾递归为未尾递归

问: 如何打开一个尾递归功能斯卡拉成非尾递归解决方案?

注意:我知道尾部递归解决方案在Scala中非常棒,但我被要求将其更改为非尾部递归解决方案。我不知道该怎么做

我有我在这里一尾递归解决方案代码(至少我希望它是尾递归笑)

def cubesTailRecur(a: List[Int], acc: List[Int] = List.empty): List[Int] = { 
     a match { 
     case Nil => acc 
     case h :: t if (h%2 == 0) => cubesTailRecur(t, acc) 
     case h :: t => cubesTailRecur(t, acc :+ Math.pow(h, 3).toInt) 
     } 
    } 

什么我的功能确实是通过给定的列表迭代的整数并返回一个新数组,其中包含所有奇数的立方体。

实施例:

println(cubesTailRecur(List(1, 2, 3, 4, 5, 6, 7))) 

    // OUTPUT 
    // List(1, 27, 125, 343) 

回答

4

尾递归是递归的一种形式,其中递归调用是最后的指令。为了不让尾部递归,意味着你需要用递归调用的结果做一些其他的计算。

对于您的情况,您可以删除acc/accumulator参数并通过递归堆栈执行累加。沿着以下几行,

def cubesRec(a: List[Int]): List[Int] = a match { 
    case Nil => List[Int]() 
    case h::t if (h%2 == 0) => cubesRec(t) 
    case h::t => Math.pow(h,3).toInt :: cubesRec(t) 
} 
+0

这有效,但有一个问题。它以相反的顺序打印列表。例如:列表(1,27,125,343)与列表(343,125,27,1) – Phillip

+0

如何反转?编辑:如何在功能中将其反转。我知道如何在印刷时反转 – Phillip

+0

你可以使用'Math.pow(h,3).toInt :: cubesRec(t)' – lztachyon