I was trying to sum all elements in a list, they are of type Option[Int], if any of them are None, the whole result is None, if all are Some(value), I want the sum of all of them:
val ls = List(Some(2), Some(5), Some(4), Some(1))
ls.fold(None)((rs,x) => for(n <- x; m <- rs) yield {n+m})
but I always get None, no matter what.
Try this also:
val ls = List(Some(2), Some(5), Some(4), Some(1))
val sum = ls.foldLeft(Option(0))((so, io) => so.flatMap(s => io.map(s + _)))
If any single value in the list is None
, then sum
is reported as None
; otherwise - if all values are defined - you get a Some
containing the sum of elements. If the list is empty, then you'd get Some(0)
as the result.