加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

从scala迭代器中消耗物品

发布时间:2020-12-16 09:11:33 所属栏目:安全 来源:网络整理
导读:我对在特征迭代器中采用的方法的行为感到困惑.看来它不消耗物品.这是一个例子: scala Iterator(1,2,3)res0: Iterator[Int] = non-empty iteratorscala res0 take 2 toArrayres1: Array[Int] = Array(1,2)scala res0.nextres2: Int = 1 显然第二步消耗两个项
我对在特征迭代器中采用的方法的行为感到困惑.看来它不消耗物品.这是一个例子:

scala> Iterator(1,2,3)
res0: Iterator[Int] = non-empty iterator

scala> res0 take 2 toArray
res1: Array[Int] = Array(1,2)

scala> res0.next
res2: Int = 1

显然第二步消耗两个项目,但是在第3步中,迭代器仍然是第一项.看看实现,我看不到任何复制或缓冲,只是一个新的迭代器代表了底层的.怎么可能?我如何设法真正消费n个物品?

解决方法

在IndexedSeqLike#Elements( source)中定义了所讨论的迭代器. A ticket was recently filed关于跨不同迭代器实现的不一致行为.

要真正消耗N个项目,请在下一次N次调用Iterator#.

你可能想考虑使用Stream,这是一个懒惰(像Iterator),但也是不可变的(不像Iterator).

scala> val s = Stream(1,3)
s: scala.collection.immutable.Stream[Int] = Stream(1,?)

scala> s.take(2).toList
res43: List[Int] = List(1,2)

scala> s.take(2).toList
res44: List[Int] = List(1,2)

scala> s.drop(2).toList
res45: List[Int] = List(3)

scala> {val (s1,s2) = s.splitAt(2); (s1.toList,s2.toList)}
res46: (List[Int],List[Int]) = (List(1,2),List(3))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读