scala迭代器和流示例。流重用失败 [英] scala iterator and stream example. stream fails on reuse

查看:131
本文介绍了scala迭代器和流示例。流重用失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码(句子 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 我可以重复使用它,理论上)。

But since I use sentences.toStream in the code above, I suppose to have stream at it is (I can reuse it, theoretically).

问:为什么会失败?

编辑:
我希望 toStream 会有所帮助。就像这里所述:( ...你可以遍历相同多次...。这就像我从未触及迭代器,我处理流。

I was hoping that toStream would help. Like was described here: (..."You can traverse the same Stream multiple times"...). It's like I never touch iterator, I have deal with stream.

但我得到了.. sentences.toStream 使用UP 句子迭代器所以我不能再使用了它。我只是期望在上执行 toStream 时iterator 执行一个逻辑,比如在不触及迭代器的情况下获取到迭代器的流 - '链接'本身。好的..

But I got.. sentences.toStream used UP sentence-iterator so I can not use it anymore. I just expected when doing toStream on iterator is do a logic like getting stream-'link' to iterator without touching iterator itself. Ok..

推荐答案

它失败了,因为句子 迭代器已经用完。除了 next 和<$ c之外,调用其上的方法之后,不应该调用 Iterator $ c> hasNext 方法。

It fails because the sentences Iterator has been expended. One is not suppose to call an Iterator after a method on it has been called except for the next and hasNext methods.

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

A simple example shows this:

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> 

在您的情况下,句子已用完第一个调用,第二个调用为空,给出大小为0.

In your case sentences has been expended on the first call and is empty on the second one giving a size of 0.

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

Calling toStream on it does not change this. You get back an empty Stream. If you want to reuse sentences assign it to a list with val l = sentences.toList before calling count.

这篇关于scala迭代器和流示例。流重用失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆