我需要遍歷列表,但循環的方式。我還需要在列表中添加新元素並遍歷所有元素(舊的和新聞元素),我該怎麼做?他們有沒有數據結構?迭代循環方式
Q
迭代循環方式
12
A
回答
7
我想也許這就是你想要的;即使您正在迭代它,也可以將新元素添加到列表中。代碼是醜陋的,但它似乎工作。
import scala.collection.mutable.Queue
class Circular[A](list: Seq[A]) extends Iterator[A]{
val elements = new Queue[A] ++= list
var pos = 0
def next = {
if (pos == elements.length)
pos = 0
val value = elements(pos)
pos = pos + 1
value
}
def hasNext = !elements.isEmpty
def add(a: A): Unit = { elements += a }
override def toString = elements.toString
}
您可以使用它像這樣:
scala> var circ = new Circular(List(1,2))
res26: Circular[Int] = Queue(1,2)
scala> circ.next
res27: Int = 1
scala> circ.next
res28: Int = 2
scala> circ.next
res29: Int = 1
scala> circ.add(5)
scala> circ.next
res30: Int = 2
scala> circ.next
res31: Int = 5
scala> circ
res32: Circular[Int] = Queue(1,2,5)
17
一種選擇是使用Stream
類來創建一個懶惰的,圓形的,無限序列:
scala> val values = List(1, 2, 3)
values: List[Int] = List(1, 2, 3)
scala> Stream.continually(values.toStream).flatten.take(9).toList
res2: List[Int] = List(1, 2, 3, 1, 2, 3, 1, 2, 3)
或者這樣說:
val values = List(1, 2, 3)
def circularStream(values: List[Int],
remaining: List[Int] = List()): Stream[Int] = {
if (remaining.isEmpty)
circularStream(values,values)
else
Stream.cons(remaining.head, circularStream(values, remaining.drop(1)))
}
circularStream(values).take(9).toList //Same result as example #1
7
這種事情真不愧是標準流庫,但似乎不是。 dbryne與流回答運作良好,或者如果您在-理解的形式
val listToRepeat:List[Foo]
val forever:Stream[Foo] = for(x<-Stream.continually(1); y<-listToRepeat) yield y
喜歡它的第一個流發生器讓事情會永遠即使你忽略的價值。第二個生成器隱式平坦化爲所需的無限流。
+1
你不需要'Stream.continually()'的參數,我認爲使用'Stream [Unit]'看起來不像'Stream [Int]'那麼混亂。 – Debilski 2010-07-15 23:31:12
10
def forever:Stream[Int] = Stream(1,2,3) append forever
+2
注意這是無限的,但不是圓形的。 – 2012-12-21 13:25:05
相關問題
- 1. 迭代循環
- 2. Jquery:循環迭代
- 3. RmarkDown迭代循環
- 4. PHP迭代循環
- 5. 迭代與循環
- 6. 迭代foreach循環
- 7. Android:循環迭代
- 8. 使用而循環使用迭代式
- 9. 循環迭代函數x次循環
- 10. 從列表循環迭代
- 11. std :: list的循環迭代
- 12. 迭代使用-的循環
- 13. ()循環迭代多少次?
- 14. 的Python for循環迭代
- 15. 循環迭代高效
- 16. C#:For循環不迭代
- 17. Excel迭代循環VBA
- 18. Underscore.js模板循環迭代
- 19. 循環這些迭代
- 20. for循環後1迭代
- 21. for循環或迭代器?
- 22. 的Java:for循環和迭代
- 23. PowerShell的循環迭代
- 24. 迭代/循環擱置
- 25. 循環索引在迭代
- 26. 與陣列迭代循環
- 27. 強制循環迭代
- 28. 無循環迭代參數
- 29. 迭代嵌套循環
- 30. 反迭代Smarty的循環
您的視頻流是無限的,但它們不是圓形。爲了使它們循環,你需要一個像'def circular [T](xs:Stream [T])這樣的技巧:Stream [T] = {lazy val knot:Stream [T] = xs#::: knot;結'} – 2012-12-21 13:24:28