gpt4 book ai didi

scala - 方法迭代器和 View 之间有什么区别?

转载 作者:行者123 更新时间:2023-12-03 09:17:59 25 4
gpt4 key购买 nike

scala> (1 to 10).iterator.map{_ * 2}.toList
res1: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

scala> (1 to 10).view.map{_ * 2}.force
res2: Seq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

除了使用next,hasNext之外,我什么时候应该选择 View 之上的迭代器或 View 之上的迭代器?

最佳答案

迭代器和 View 之间存在巨大差异。迭代器仅使用一次,即可按需计算,而 View 多次使用,每次都重新计算,但仅需要元素。例如:

scala> val list = List(1,2,3).map{x => println(x); x * 2}
1
2
3
list: List[Int] = List(2, 4, 6)

scala> list(2)
res14: Int = 6

scala> list(2)
res15: Int = 6

scala> val view = List(1,2,3).view.map{x => println(x); x * 2}
view: scala.collection.SeqView[Int,Seq[_]] = SeqViewM(...)

scala> view(2)
3
res12: Int = 6

scala> view(2)
3
res13: Int = 6

scala> val iterator = List(1,2,3).iterator.map{x => println(x); x * 2}
iterator: Iterator[Int] = non-empty iterator

scala> iterator.drop(2).next
1
2
3
res16: Int = 6

scala> iterator.drop(2).next
[Iterator.next] (Iterator.scala:29)
(access lastException for the full trace)

关于scala - 方法迭代器和 View 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4798043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com