我想创建一个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
Run Code Online (Sandbox Code Playgroud)
huy*_*hjl 27
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)
Run Code Online (Sandbox Code Playgroud)
哪个印刷品:
eval 1
1
eval 2
2
eval 3
Run Code Online (Sandbox Code Playgroud)
因此,如果确定计算是否应该继续的条件可以在计算之外进行评估,那么这非常有效.
基本上我想我Iterator.continually(getNext()).takeWhile(_ != certainValue)会说会实现你想要做的事情.这是懒惰的评价.
你看过scala.collection.immutable.Stream吗?它的目的是创建一个像对象的序列,其中下一个元素被懒惰地评估.它可以是有限的或无限的.
例如:
Welcome to Scala version 2.9.0.final (Java HotSpot(TM) Client VM, Java 1.6.0_24).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import collection.immutable._
import collection.immutable._
scala> def next(i: Int): Stream[Int] = Stream.cons(i*i, next(i*i))
next: (i: Int)scala.collection.immutable.Stream[Int]
scala> val stream = next(2)
stream: scala.collection.immutable.Stream[Int] = Stream(4, ?)
scala> stream.find(_ > 1000)
res0: Option[Int] = Some(65536)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9060 次 |
| 最近记录: |