# What combinator to use? scanLeft but not every iteration

**URL:** <https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763>\
**Category:** Question\
**Created:** [May 14, 2025, 8:42am UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763 "2025-05-14T08:42:58Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![Norm\_2](https://users.scala-lang.org/letter_avatar_proxy/v4/letter/n/90ced4/32.png) [@Norm\_2](https://users.scala-lang.org/u/Norm_2)\
**Post date:** [May 14, 2025, 8:42am UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/1 "2025-05-14T08:42:58Z")

</div>

Given a list of integers

```scala
Seq(2,4,6,1,2,2,3,7,4,4,4)

```

produce a new list where all consecutive even numbers are summed, and intervening odd numbers are kept unchanged.

```scala
Seq(2,4,6,1,2,2,3,7,4,4,4).fn(???) = Seq(12,1,4,3,7,12)
// ((2 + 4 + 6) = 12, 1, (2 + 2) = 4, 3, 7, (4 + 4 + 4) = 12)

```

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.

---

<div class="post-metadata">

**Author:** ![anqit](https://users.scala-lang.org/user_avatar/users.scala-lang.org/anqit/32/2368_2.png) [@anqit](https://users.scala-lang.org/u/anqit)\
**Post date:** [May 14, 2025, 12:58pm UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/2 "2025-05-14T12:58:14Z")

</div>

Here’s a take at it doing the recursion explicitly:

> **[Scastie - An interactive playground for Scala.](https://scastie.scala-lang.org/bcrCXccbTEu0eKo2CwWgUA)**
>
> def sumEvens(ints: List\[Int\]): List\[Int\] =
> def go(is: List\[Int\], acc: List\[Int\], curr: Option\[Int\]): List\[Int\] =
> (is, curr) match
> case (i :: rest, c) if i % 2 == 0 =\>
> go(rest, acc, Some(i + c.getOrElse(0)))
> case (i ::...

---

<div class="post-metadata">

**Author:** ![Jasper-M](https://users.scala-lang.org/user_avatar/users.scala-lang.org/jasper-m/32/872_2.png) [@Jasper-M](https://users.scala-lang.org/u/Jasper-M)\
**Post date:** [May 14, 2025, 1:09pm UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/3 "2025-05-14T13:09:56Z")

</div>

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:

```scala
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
}

```

---

<div class="post-metadata">

**Author:** ![anqit](https://users.scala-lang.org/user_avatar/users.scala-lang.org/anqit/32/2368_2.png) [@anqit](https://users.scala-lang.org/u/anqit)\
**Post date:** [May 14, 2025, 1:15pm UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/4 "2025-05-14T13:15:57Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Jasper-M](https://users.scala-lang.org/user_avatar/users.scala-lang.org/jasper-m/32/872_2.png) [@Jasper-M](https://users.scala-lang.org/u/Jasper-M)\
**Post date:** [May 14, 2025, 1:19pm UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/5 "2025-05-14T13:19:29Z")

</div>

> [@anqit](#):
>
> 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.

That is indeed a problem. It’s probably not worth the effort to try to fit it in `foldLeft`.

---

<div class="post-metadata">

**Author:** ![philipschwarz](https://users.scala-lang.org/user_avatar/users.scala-lang.org/philipschwarz/32/3130_2.png) [@philipschwarz](https://users.scala-lang.org/u/philipschwarz)\
**Post date:** [May 14, 2025, 5:46pm UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/6 "2025-05-14T17:46:32Z")

</div>

FWIW, had a go at this approach:

```Scala
def f(list: List[Int]) = LazyList.unfold(list){
  case Nil => None
  case x::xs if x % 2 == 1 => Some(x, xs)
  case xs => xs.span(_ % 2 == 0) match { case (even, rest) => Some(even.sum, rest) }
}.toList

val ints = List(2,4,6,1,2,2,3,7,4,4,4)

assert(f(ints) == List(12,1,4,3,7,12))

```

---

<div class="post-metadata">

**Author:** ![som-snytt](https://users.scala-lang.org/letter_avatar_proxy/v4/letter/s/7cd45c/32.png) [@som-snytt](https://users.scala-lang.org/u/som-snytt)\
**Post date:** [May 15, 2025, 12:12am UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/7 "2025-05-15T00:12:13Z")

</div>

TIL `LazyList.unfold` claims to be “significantly simpler than `Iterator.unfold`”, but I guess that is in the eye of the beholder.

Arranging deck chairs:

```auto
def evenSum(xs: List[Int]): List[Int] =
  List.unfold(xs):
    _.span(_ % 2 == 0) match
    case (Nil, x :: xs) => Some(x, xs)
    case (Nil, _) => None
    case (evens, xs) => Some(evens.sum, xs)

@main def test = println:
  evenSum:
    List(2,4,6,1,2,2,3,7,4,4,4)

```

I was curious to see if this compiled, because of recent discussion about `PartialFunction` synthesis:

```auto
def pf: PartialFunction[List[Int], Option[(Int, List[Int])]] =
    _.span(_ % 2 == 0) match
    case (Nil, x :: xs) => Some(x, xs)
    case (Nil, _) => None
    case (evens, xs) => Some(evens.sum, xs)

```

It compiles but (in file `even-sums.scala`):

```auto
➜ snips scala-cli run --server=false -S 3.7.0 even-sums.scala
Exception in thread "main" java.lang.ClassFormatError: Duplicate method name "even$minussums$package$$$_$_$$anonfun$$anonfun$1" with signature "(I)Z" in class file even$minussums$package$

```

Oh I bet that is [this recent issue](https://github.com/scala/scala3/issues/23054).

With a symbol like `even$minussums$package$$$_$_$$anonfun$$anonfun$1`, it must be “code golfing for dollars”.

---

<div class="post-metadata">

**Author:** ![Ichoran](https://users.scala-lang.org/user_avatar/users.scala-lang.org/ichoran/32/550_2.png) [@Ichoran](https://users.scala-lang.org/u/Ichoran)\
**Post date:** [May 15, 2025, 2:09am UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/8 "2025-05-15T02:09:44Z")

</div>

Sometimes questions like these appear in a mutable context and just get carried over to an immutable one without really deciding whether it’s the kind of thing one would do.

If Scala had a built-in group-by-equivalence-class method, which it doesn’t, then it would be a simple matter of expressing that even values are equivalent to each other and odd values aren’t equivalent to anything. (e.g. `(a % 2) | (b %2) == 0` would be the equivalence criterion).

You can fake it with `scan`.

```scala
val ecs = xs.scan(0){ (c, x) => if x % 2 == 0 then (c + 1) & ~1 else (c + 1) | 1 }.drop(1)

```

(The odd bit math is there to make sure odd values have odd equivalence class numbers which keep increasing, while even values advance to an even equivalence class number and then stay there.)

Now we can use `groupBy` to actually gather the elements.

```scala
val sums = (ecs zip xs).groupBy(_._1).mapValues(_.map(_._2).sum).toSeq.sortBy(_._1).map(_._2)

```

So, overall, it’s kind of a two-liner. Not a very pretty two-liner, granted.

But it really ought to be

```scala
xs.chunkWith((a, b) => ((a % 2) | (b % 2)) == 0).map(_.sum)

```

Given that the scan/groupBy version is pretty messy, it’s worth considering

```scala
var sum = 0
val ysb = Seq.newBuilder[Int]
for (a, b) <- xs.zipAll(xs.drop(1), 0, 1) do
  if a % 2 == 0 then
    sum += a
    if b % 2 != 0 then ysb += sum
  else
    sum = 0
    ysb += a
val ys = ysb.result

```

(If you had an indexable sequence, you’d probably index instead of using the `zipAll` trick.)

---

<div class="post-metadata">

**Author:** ![Norm\_2](https://users.scala-lang.org/letter_avatar_proxy/v4/letter/n/90ced4/32.png) [@Norm\_2](https://users.scala-lang.org/u/Norm_2)\
**Post date:** [May 15, 2025, 2:31am UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/9 "2025-05-15T02:31:43Z")

</div>

> [@Ichoran](#):
>
> Sometimes questions like these appear in a mutable context and just get carried over to an immutable one without really deciding whether it’s the kind of thing one would do.

The context is a parser, where I am taking a string like `"hello world friend "` and turning it into the sequence `Seq("hello", " ", " ", "world", " ", "friend", " ", " ", " ")`

The “even/odd numbers” analogy is:  
“even” → consecutive letters (not spaces)  
“odd” → the spaces themselves.

So it’s like, `string.takeWhile(notSpace)` but `takeWhile` would stop immediately when `" "` is found and not include that `" "`; I want it to keep going throughout the entire string, concatenating letters but keeping spaces unchanged.

```scala
Seq(
  'h' + 'e' + 'l' + 'l' + 'o',
  " ",
  " ",
  'w' + 'o' + 'r' + 'l' + 'd',
  " ",
  'f' + 'r' + 'i' + 'e' + 'n' + 'd',
  " ", 
  " ",
  " "
)

```

I can solve this using recursion but prefer a 1-liner.

---

<div class="post-metadata">

**Author:** ![Ichoran](https://users.scala-lang.org/user_avatar/users.scala-lang.org/ichoran/32/550_2.png) [@Ichoran](https://users.scala-lang.org/u/Ichoran)\
**Post date:** [May 15, 2025, 4:24am UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/10 "2025-05-15T04:24:43Z")

</div>

> [@Norm\_2](#):
>
> The context is a parser

Parsers run like molasses if you’re treating them a character at a time. Now, if you’re not parsing much, it’s _okay_ if they run like molasses.

If you actually have a parsing problem, you probably should use a parsing library like [fastparse](https://com-lihaoyi.github.io/fastparse/).

If you want to chop strings into pieces, use the `.split` method on `String`.

If you’re just using this to gain experience, well, congrats! You have discovered that it is a bit frustrating to not have a chunk/fragment method.

---

<div class="post-metadata">

**Author:** ![Norm\_2](https://users.scala-lang.org/letter_avatar_proxy/v4/letter/n/90ced4/32.png) [@Norm\_2](https://users.scala-lang.org/u/Norm_2)\
**Post date:** [May 15, 2025, 4:55am UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/11 "2025-05-15T04:55:13Z")

</div>

> [@Ichoran](#):
>
> Parsers run like molasses if you’re treating them a character at a time. Now, if you’re not parsing much, it’s _okay_ if they run like molasses.

It’s for a compiler. I’m not sure how it would be logically possible to avoid parsing 1 character at a time. Every compiler I’ve seen does this in the lexer, except they usually do it imperatively with `i` and `j` vars within a `while`. Isn’t it definitional to the problem that you have to scan each individual character? I would assume those parse libraries just abstract over that process.

---

<div class="post-metadata">

**Author:** ![som-snytt](https://users.scala-lang.org/letter_avatar_proxy/v4/letter/s/7cd45c/32.png) [@som-snytt](https://users.scala-lang.org/u/som-snytt)\
**Post date:** [May 15, 2025, 5:28am UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/12 "2025-05-15T05:28:04Z")

</div>

Thanks! I remembered you said on gitter several years ago that you write this all the time, and in fact I looked in kse just in kase.

My suggestion for a pronunciation, however, since you mention on the project page that it has none, would be `KerrSE`, like an acronym out of a James Bond movie.

---

<div class="post-metadata">

**Author:** ![Ichoran](https://users.scala-lang.org/user_avatar/users.scala-lang.org/ichoran/32/550_2.png) [@Ichoran](https://users.scala-lang.org/u/Ichoran)\
**Post date:** [May 15, 2025, 5:36am UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/13 "2025-05-15T05:36:05Z")

</div>

> [@Norm\_2](#):
>
> I’m not sure how it would be logically possible to avoid parsing 1 character at a time.

Do it in `Array[Char]` and `String`, so you’re using primitives (efficiently). Or use a library like fastparse, which is a little slower but a lot easier and uses primitives wherever possible. Trying to use generic immutable sequence operations, where you have to individually box every character, is not the way to do it. For compiler parsers you generally can’t afford a 100x slowdown.

---

<div class="post-metadata">

**Author:** ![Ichoran](https://users.scala-lang.org/user_avatar/users.scala-lang.org/ichoran/32/550_2.png) [@Ichoran](https://users.scala-lang.org/u/Ichoran)\
**Post date:** [May 15, 2025, 5:49am UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/14 "2025-05-15T05:49:02Z")

</div>

I don’t remember that, but I do have `diced` on my set of array operations (in basics/src/Data.scala), and I can find the boundaries with `whereOp`. So when writing it myself, I’d

```scala
val boundaries = xs.whereOp: (x, i) =>
  if x % 2 == 1 || (i > 0 && xs(i-1) % 2 == 1) then i else -1
xs.diced(boundaries, "[)").map(_.sum)

```

---

<div class="post-metadata">

**Author:** ![Jasper-M](https://users.scala-lang.org/user_avatar/users.scala-lang.org/jasper-m/32/872_2.png) [@Jasper-M](https://users.scala-lang.org/u/Jasper-M)\
**Post date:** [May 15, 2025, 8:18am UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/15 "2025-05-15T08:18:43Z")

</div>

Just for fun, you can also use a `fs2.Stream`:

```scala
import fs2.Stream
import cats.syntax.all._

val list = List(2,4,6,1,2,2,3,7,4,4,4)

Stream.emits(list).groupAdjacentBy(_ % 2).flatMap {
  case (0, chunk) => Stream.emit(chunk.sumAll)
  case (_, chunk) => Stream.chunk(chunk)
}.toList

```

---

<div class="post-metadata">

**Author:** ![LannyRipple](https://users.scala-lang.org/user_avatar/users.scala-lang.org/lannyripple/32/65_2.png) [@LannyRipple](https://users.scala-lang.org/u/LannyRipple)\
**Post date:** [May 20, 2025, 5:27pm UTC](https://users.scala-lang.org/t/what-combinator-to-use-scanleft-but-not-every-iteration/10763/16 "2025-05-20T17:27:33Z")

</div>

You really only need to find the beginning.

```auto
xs.foldLeft(List.empty[Int]) {
    case (Nil, n) => List(n)
    case (h :: ts, n) if h % 2 == 0 && n % 2 == 0 => n + h :: ts
    case (h :: ts, n) => n :: h :: ts
}
  .reverse

```
