Reputation: 3562
This may be a weird question but...
Question: How do I turn a tail-recursive function in Scala into a non-tail-recursive solution?
Note: I am aware tail recursive solutions are great in Scala, but I was asked to change it into a non-tail recursive solution. I have no idea how to do that
I have my code for a tail-recursive solution here (at least I hope it's tail recursive lol)
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)
}
}
What my function does is iterate through a given List of integers and returns a new array with the cubes of all the odd numbers.
Example:
println(cubesTailRecur(List(1, 2, 3, 4, 5, 6, 7)))
// OUTPUT
// List(1, 27, 125, 343)
Upvotes: 0
Views: 173
Reputation: 116
Tail recursion is a form of recursion in which recursive call is the last instruction. To not make something tail recursive would mean that you need to do some other computation with the result of the recursive call.
In your case, you can remove the acc
/accumulator parameter and perform accumulation through recursive stack. Something along the following lines,
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)
}
Upvotes: 4