I am trying to understand foldM
of Foldable
in cats
trying a simple example: suppose I need to sum up the numbers in a list while the running sum is positive and break when it is not.
val sumUp: (Int, Int) => Option[Int] = (x, y) => {
println(s"x = $x, y = $y")
val sum = x + y
if (sum > 0) Some(sum) else None
}
scala> val xs = List(1, 2, 3, -2, -5, 1, 2, 3)
xs: List[Int] = List(1, 2, 3, -2, -5, 1, 2, 3)
scala> Foldable[Stream].foldM(xs.toStream, 0)(sumUp)
x = 0, y = 1
x = 1, y = 2
x = 3, y = 3
x = 6, y = -2
x = 4, y = -5
res27: Option[Int] = None
Now I need to write new function sumUp2
to get the input stream tail, which starts where the running sum becomes <= 0 and the foldM
breaks. For example, I need to get something like this:
scala> val tail = Foldable[Stream].foldM(xs.toStream, 0)(sumUp2)
tail: Stream[Int] = Stream(-5, ?)
scala>tail.toList
res28: List[Int] = List(-5, 1, 2, 3)
How to write sumUp2
?