I’m trying to write a scala function which will recursively sum the values in a list. Here is what I have so far :
def sum(xs: List[Int]): Int = {
val num = List(xs.head)
if(!xs.isEmpty) {
sum(xs.tail)
}
0
}
I dont know how to sum the individual Int values as part of the function. I am considering defining a new function within the function sum and have using a local variable which sums values as List is beuing iterated upon. But this seems like an imperative approach. Is there an alternative method ?
Here’s the the “standard” recursive approach:
And, here’s a tail-recursive function. It will be more efficient than a non-tail-recursive function because the compiler turns it into a while loop that doesn’t require pushing a new frame on the stack for every recursive call: