Reputation: 1280
How can i count my List
items value using recursion and return the sum of all my List
elements total value ??
def getTotalValue(list: ListBuffer[Double], val: Double): Double = {
list.foreach(x => {
val += x
})
}
Upvotes: 0
Views: 832
Reputation: 20405
To illustrate the plain recursion (non tail recursion) consider
def f(xs: List[Double]): Double = if (xs.isEmpty) 0D else xs.head + f(xs.tail)
where we return 0.0
whenever the current list is empty, or else we sum up the head value of the current list with the (recursive) call to f
with the rest of the current list.
By decreasing monotonically the size of the list in each recursive call it is guaranteed the trivial case (the empty list) is eventually reached and hence any type-safe call to this function terminates. Moreover, the function is well defined, it covers both empty and non empty list cases.
Upvotes: 1
Reputation: 85
Try this
import scala.annotation.tailrec
def getTotal(list: List[Int]) = {
@tailrec
def get(list: List[Int], total: Int): Int = list match {
case head :: tail => get(tail, total + head)
case Nil => total
}
get(list, 0)
}
getTotal(List(90,8,98,10,-3)) // should be return 203
getTotal(List(15,10,20,10)) // should be return 55
Upvotes: 1
Reputation: 6193
This should work for any Sequence (List and ListBuffer)
@tailrec
def getTotalValue(list: Seq[Double], value: Double): Double =
list.headOption match {
case Some(v) => getTotalValue(list.tail, value + v)
case None => value
}
E.g. to use it:
getTotalValue(ListBuffer(1,2,3,4), 0)
getTotalValue(List(1,2,3,4), 0)
will return 10.0
If you want something specific to List, you can take advantage of the cons (::) operator to match to head :: tail instead of using headOption.
( Although, I assume you are doing this more for academic purposes. An easier way to sum the values would be to use sum. E.g. List(1,2,3,4).sum )
Upvotes: 1