【问题标题】:scala iterator and stream example. stream fails on reusescala 迭代器和流示例。流在重用时失败
【发布时间】:2013-06-04 23:05:28
【问题描述】:

我有一个代码(sentences 在这里是iterator):

  def count() = {
    var count = 0
    for(sentence <- sentences.toStream) count += sentence.words.size
    count
  }

和测试:

// first
val wordCount1 = wordCounter.count()
wordCount1 must_== 10

// second time - should be same result
val wordCount2 = wordCounter.count()
wordCount2 must_== 10   // fails: result is 0

上次测试失败:

'0' is not equal to '10'
Expected :10
Actual   :0

但由于我在上面的代码中使用了sentences.toStream,我想stream 是(理论上我可以重用它)。

问:为什么会失败?


编辑: 我希望toStream 会有所帮助。正如here 所描述的那样:(...“您可以多次遍历相同的Stream”...)。就像我从不接触迭代器一样,我处理的是流。

但是我得到了.. sentences.toStream 用完了 sentence-iterator 所以我不能再使用它了。我只是期望在iterator 上执行toStream 时会执行一种逻辑,例如在不触及迭代器本身的情况下将流“链接”到迭代器。好的..

【问题讨论】:

    标签: scala stream iterator


    【解决方案1】:

    失败是因为sentences Iterator 已用完。除了nexthasNext 方法之外,不应在调用Iterator 的方法后调用它。

    一个简单的例子说明了这一点:

    scala> val it = Iterator(1,2,3)
    it: Iterator[Int] = non-empty iterator
    
    scala> it.foreach(println(_))
    1
    2
    3
    
    scala> it.foreach(println(_))
    
    scala> 
    

    在您的情况下,sentences 已在第一次调用中使用,而在第二次调用中为空,大小为 0。

    调用toStream 不会改变这一点。你会得到一个空的Stream。如果您想重用 sentences,请在调用 count 之前将其分配给带有 val l = sentences.toList 的列表。

    【讨论】:

      【解决方案2】:

      其实toStream 有帮助。我只是将代码更改为期望 stream 而不是 iterator,以便不尝试在 second+ 遍历时从“死”迭代器创建流。

      那我的解决办法是:

      val stream = new SentenceFileReader("two_lines_file.txt").toStream
      
      val wordCounter = new WordCounter(stream) // now it accepts stream but not iterator
      
      // first
      val wordCount1 = wordCounter.count()
      wordCount1 must_== 10
      
      // second time - same result
      val wordCount2 = wordCounter.count()
      wordCount2 must_== 10
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-04
        • 1970-01-01
        • 2021-04-21
        • 1970-01-01
        • 1970-01-01
        • 2013-04-29
        • 1970-01-01
        • 2018-07-28
        相关资源
        最近更新 更多