user701254 - 2 months ago 10x

Scala Question

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 ?

Answer

Here's the the "standard" recursive approach:

```
def sum(xs: List[Int]): Int = {
xs match {
case x :: tail => x + sum(tail) // if there is an element, add it to the sum of the tail
case Nil => 0 // if there are no elements, then the sum is 0
}
}
```

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:

```
def sum(xs: List[Int]): Int = {
@tailrec
def inner(xs: List[Int], accum: Int): Int = {
xs match {
case x :: tail => inner(tail, accum + x)
case Nil => accum
}
}
inner(xs, 0)
}
```

Source (Stackoverflow)

Comments