use*_*187 21 scala scala-collections scala-2.10
Scala集合中是否提供循环队列?
我需要重复迭代一个循环自己的列表
val x = new CircularList(1,2,3,4)
x.next (returns 1)
x.next (returns 2)
x.next (returns 3)
x.next (returns 4)
x.next (returns 1)
x.next (returns 2)
x.next (returns 3)
Run Code Online (Sandbox Code Playgroud)
... 等等
Tra*_*own 40
使用continually
和滚动自己很容易flatten
:
scala> val circular = Iterator.continually(List(1, 2, 3, 4)).flatten
circular: Iterator[Int] = non-empty iterator
scala> circular.take(17).mkString(" ")
res0: String = 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
Run Code Online (Sandbox Code Playgroud)
还有一种continually
方法 - Stream
如果要生成大量元素,请注意不要保留对流的头部的引用.
gou*_*ama 12
您可以使用a轻松创建循环列表Stream
.
scala> val l = List(1,2,3,4).toStream
l: scala.collection.immutable.Stream[Int] = Stream(1, ?)
scala> def b: Stream[Int] = l #::: b
b: Stream[Int]
scala> b.take(20).toList
res2: List[Int] = List(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)
Run Code Online (Sandbox Code Playgroud)
编辑:您希望确保预先定义重复的部分,一次且仅一次,以避免吹堆(结构共享Stream
).如:
def circular[A](a: Seq[A]): Stream[A] = {
val repeat = a.toStream
def b: Stream[A] = repeat #::: b
b
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5266 次 |
最近记录: |