Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何创建内容为表达式结果的有限迭代器?_Scala - Fatal编程技术网

Scala 如何创建内容为表达式结果的有限迭代器?

Scala 如何创建内容为表达式结果的有限迭代器?,scala,Scala,我想创建一个迭代器,它通过(反复)计算表达式来获取下一个元素,我希望表达式能够返回某个值来终止它 我发现的唯一一件事是,它似乎是无限的。重要的是,在迭代器上调用next()之前,不应计算表达式 有没有办法让这种行为发生 例如: def getNext = { // some complicated code val next = ... // either a STOP value or a real value to be returned by the iterator } va

我想创建一个
迭代器
,它通过(反复)计算表达式来获取下一个元素,我希望表达式能够返回某个值来终止它

我发现的唯一一件事是,它似乎是无限的。重要的是,在
迭代器上调用
next()
之前,不应计算表达式

有没有办法让这种行为发生

例如:

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
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)
你看过吗?它的目的是创建一个类似于序列的对象,其中下一个元素被惰性地计算。它可以是有限的,也可以是无限的

例如:

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
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)

Iterator.continuously
通常与
takeWhile
组合使用:

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

val iter = Iterator.continually { complexCompute() }
iter.takeWhile(_ < 3).foreach(println)
因此,如果决定计算是否应该继续的条件可以在计算之外进行评估,那么这就非常有效


基本上,我想我说的是
Iterator.continuously(getNext()).takeWhile(!=certainValue)
将实现您想要做的事情。它是惰性计算的。

迭代器在看到停止值时应该返回什么?它不应该返回更多的项。我认为当涉及递归时,这非常有效。否则,我更喜欢迭代器,因为流、大量数据和保留对th流头部的引用存在某些缺陷。