gpt4 book ai didi

Scala 迭代器 : "one should never use an iterator after calling a method on it" - why?

转载 作者:行者123 更新时间:2023-12-04 23:03:00 26 4
gpt4 key购买 nike

关于迭代器的 Scala 文档[T] here说如下:

It is of particular importance to note that, unless stated otherwise, one should never use an iterator after calling a method on it. The two most important exceptions are also the sole abstract methods: next and hasNext.



他们还给出了安全和不安全使用的具体示例:
def f[A](it: Iterator[A]) = {
if (it.hasNext) { // Safe to reuse "it" after "hasNext"
it.next // Safe to reuse "it" after "next"
val remainder = it.drop(2) // it is *not* safe to use "it" again after this line!
remainder.take(2) // it is *not* safe to use "remainder" after this line!
} else it
}

不幸的是,我在这里不遵循不安全的想法。有人可以在这里为我解释一下吗?

最佳答案

这是一个具体的例子:

def eleventh[A](xs: Iterator[A]) = {
xs.take(10).toList
xs.next
}

我们可以试试:
scala> eleventh((1 to 100).toList.toIterator)
res0: Int = 11

scala> eleventh((1 to 100).toStream.toIterator)
res1: Int = 11

scala> eleventh(Stream.from(1).toIterator)
res2: Int = 11

看起来不错。但是之后:
scala> eleventh((1 to 100).toIterator)
res3: Int = 1

现在 (1 to 100).toIterator(1 to 100).toList.toIterator 的类型相同,但两者在这里的行为非常不同——我们看到实现细节从 API 中泄露出来。这是一件非常糟糕的事情,是混合像 take 这样的纯函数组合器的直接结果。具有固有的命令式和可变概念,例如迭代器。

关于Scala 迭代器 : "one should never use an iterator after calling a method on it" - why?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18420995/

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