从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)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- angularjs – 有没有办法可以简化angular-ui-router解决方案
- bootstrap-datetimepicker的运用点滴
- 系统运行进程相关的Shell命令
- 如何在Angular2中注入相同组件的新实例
- bootstrap-媒体对象列表
- 接口错误日志查询(SRT_UTIL)
- Bash的登录与欢迎信息: \/etc\/issue & 	
- angularjs – 如何将参数传递给角度js中的过滤器函数
- scala – SBT – 使用汇编时的多项目合并策略和构建sbt结构
- angularjs – 如何翻译Angular-UI-Bootstrap datepicker?