Scala version of Rubys' each_slice?

collections, ruby, scala, scala-2.8

Solution

Scala 2.8 has `grouped` that will chunk the data in blocks of size `n` (which can be used to achieve `each_slice` functionality):

scala> val a = Array(1,2,3,4,5,6)
a: Array[Int] = Array(1, 2, 3, 4, 5, 6)

scala> a.grouped(2).foreach(i => println(i.reduceLeft(_ + _)) )
3
7
11

There isn't anything that will work out of the box in 2.7.x as far as I recall, but it's pretty easy to build up from `take(n)` and `drop(n)` from `RandomAccessSeq`:

def foreach_slice[A](s: RandomAccessSeq[A], n: Int)(f:RandomAccessSeq[A]=>Unit) {
  if (s.length <= n) f(s)
  else {
    f(s.take(n))
    foreach_slice(s.drop(n),n)(f)
  }
}

scala> val a = Array(1,2,3,4,5,6)
a: Array[Int] = Array(1, 2, 3, 4, 5, 6)

scala> foreach_slice(a,2)(i => println(i.reduceLeft(_ + _)) )                 
3
7
11

Problem

Does Scala have a version of Rubys' each_slice from the Array class?

Original source