Bef*_*rem 8 ruby collections scala scala-2.8
Scala是否有Array类中的Rubys'pert_slice版本?
Rex*_*err 12
Scala 2.8具有grouped
以块大小n
(可用于实现each_slice
功能)的数据块:
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
Run Code Online (Sandbox Code Playgroud)
没有任何东西,将制定出在2.7.x盒子,据我记得,但它是很容易从建立take(n)
和drop(n)
来自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
Run Code Online (Sandbox Code Playgroud)
使用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)
Run Code Online (Sandbox Code Playgroud)