Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala version of Rubys' each_slice?

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

like image 296
BefittingTheorem Avatar asked Mar 16 '10 16:03

BefittingTheorem


2 Answers

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
like image 110
Rex Kerr Avatar answered Oct 31 '22 01:10

Rex Kerr


Tested with Scala 2.8:

scala> (1 to 10).grouped(3).foreach(println(_))
IndexedSeq(1, 2, 3)
IndexedSeq(4, 5, 6)
IndexedSeq(7, 8, 9)
IndexedSeq(10)
like image 6
retronym Avatar answered Oct 31 '22 02:10

retronym