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))))