Sum a list of options in Scala using tail recursion and match expressions

Viewed 246

i have to make a tail recursive program using match expressions which will print the sum of List of type List[Option[Double]] f.e List(Some(1), ..., Some(n)) --> Some(1 + ... + n) But it only sum the list which have a positive number so when Some(d) and d < 0 it doesnt count.

List(Some(1.0),Some(2.0), Some(-3.0) ---> Some(3.0)

When there are not any elements which are positive it should return None

sumuj(List(Some(2.0), Some(4.0), Some(-3.0), None, Some(-3.0), None, Some(1.0))) returns Some(7.0)

I only know how to sum list only of Some(value), do not know how to sum only positive arguments.

def sumuj(l: List[Option[Double]]): Option[Double] = {
  def helper(l: List[Option[Double]], acc: Double): Option[Double] = {
    l match {
      case head :: tail => head match {
        case Some(value)  => helper(tail, acc + value)
      }
      case Nil => Some(acc)
    }
  }
  helper(l, acc = 1)
}
println(sumuj(List(Some(2.0), Some(4.0), Some(-3.0))))
1 Answers

You can use a pattern match guard for that:

def sumPositives(l: List[Option[Double]]) = {
  @tailrec
  def sumPositives0(l: List[Option[Double]], acc: Double): Option[Double] =
    l match {
      case Some(head) :: tail if head > 0 => sumPositives0(tail, acc + head)
      case _ :: tail                      => sumPositives0(tail, acc)
      case Nil                            => Some(acc)
    }
  sumPositives0(l, acc = 1)
}

And then:

println(sumPositives(List(Some(2.0), Some(4.0), Some(-3.0))))

Yields:

Some(7.0)
Related