gpt4 book ai didi

scala - 如何创建内容是表达式结果的有限迭代器?

转载 作者:行者123 更新时间:2023-12-03 14:38:11 26 4
gpt4 key购买 nike

我想创建一个Iterator通过(反复地)对一个表达式求值来获取其下一个元素,并且我希望该表达式能够返回某个值来终止它。

我发现的唯一的东西是Iterator.continually(),它似乎是无限的。重要的是,在next()上调用Iterator之前,不应该对表达式求值。

有没有办法获得这种行为?

例如:

def getNext = {
// some complicated code
val next = ... // either a STOP value or a real value to be returned by the iterator
}

val myIter = Iterator.continually(getNext) // want this to stop at some point

最佳答案

Iterator.continually通常与takeWhile结合使用:

var count = 0
def complexCompute(): Int = { count +=1; println("eval " + count); count }

val iter = Iterator.continually { complexCompute() }
iter.takeWhile(_ < 3).foreach(println)


哪些打印:

eval 1
1
eval 2
2
eval 3


因此,如果可以在计算之外评估确定是否应继续进行计算的条件,则此方法效果很好。

基本上我想我说的是 Iterator.continually(getNext()).takeWhile(_ != certainValue)将实现您想要的目标。懒洋洋的评价。

关于scala - 如何创建内容是表达式结果的有限迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6165152/

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