What combinator to use? scanLeft but not every iteration

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:

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:

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

➜  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.

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

3 Likes