It seems to be a mix of scanning and takeWhile, except the scan combinators take snapshots every iteration while we need to only take one snapshot per group of consecutive even numbers.
I don’t think there’s one specific combinator for this use case. You could probably use foldleft or foldRight, but it will look just like @anqit’s solution without the explicit recursion.
With span you could simplify your custom combinator a bit:
def combine(list: List[Int]): List[Int] = {
val (evens, rest) = list.span(_ % 2 == 0)
if (evens.nonEmpty) evens.sum :: combine(rest)
else if (rest.nonEmpty) rest.head :: combine(rest.tail)
else Nil
}
TIL List#span, cool!
I tried a solution with foldLeft/Right, but the issue I had was not knowing when you were at the last element of the list (in either direction) and being able to handle adding the last element.