gpt4 book ai didi

Scala Iterator.takeWhile 正在删除失败的元素

转载 作者:行者123 更新时间:2023-12-05 01:44:01 26 4
gpt4 key购买 nike

val i = (1 to 8).toIterator
val oneToThree = i.takeWhile(_ <= 3).toList
// List(1, 2, 3)

到目前为止一切顺利。现在我希望迭代器仍然包含 (3, 4, 5, 6, 7, 8),但如果我继续:

val fourToSix = i.takeWhile(_ <= 6).toList
// List(5, 6)

元素 3 已丢失。我希望 fourToSix 成为 List(4, 5, 6)。我怎样才能使用 takeWhile 或一些类似的操作来让它工作?

最佳答案

请注意关于takeWhile 的文档指出:

Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

所以你不应该在调用 takeWhile 之后使用 i


但是要实现你想要的,你可以使用 span 方法:

scala> val i = (1 to 8).iterator
i: Iterator[Int] = non-empty iterator

scala> val (oneToThree, rest) = i.span(_ <= 3)
oneToThree: Iterator[Int] = non-empty iterator
rest: Iterator[Int] = unknown-if-empty iterator

scala> oneToThree.toList
res1: List[Int] = List(1, 2, 3)

scala> val fourToSix = rest.takeWhile(_ <= 6)
fourToSix: Iterator[Int] = non-empty iterator

scala> fourToSix.toList
res2: List[Int] = List(4, 5, 6)

关于Scala Iterator.takeWhile 正在删除失败的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47717671/

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