Does Scala have a version of Rubys' each_slice from the Array class?
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With