如何创建一个内容是表达式结果的有限迭代器? [英] How to create a finite iterator with contents being a result of an expression?

查看:32
本文介绍了如何创建一个内容是表达式结果的有限迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个 Iterator,它通过(重复)评估一个表达式来获取其下一个元素,并且我希望该表达式能够返回某个值来终止它.>

我唯一发现的类似情况是 Iterator.continually(),这似乎是无限的.重要的是,在 Iterator 上调用 next() 之前不应计算表达式.

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

例如:

def getNext = {//一些复杂的代码val next = ...//迭代器要返回的停止值或实际值}val myIter = Iterator.continually(getNext)//希望在某个时间点停止

解决方案

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

var count = 0def complexCompute(): Int = { count +=1;println("评估" + 计数);数数 }val iter = Iterator.continually { complexCompute() }iter.takeWhile(_ < 3).foreach(println)

打印:

eval 11评估 22评估 3

因此,如果可以在计算之外评估确定是否应继续计算的条件,那么这很有效.

基本上我想我是说 Iterator.continually(getNext()).takeWhile(_ != sureValue) 将实现您想要做的事情.它被懒惰地评估.

I'd like to create an Iterator that gets its next element by (repeatedly) evaluating an expression, and I want the expression to be able to return a certain value to terminate it.

The only thing I've found like this is Iterator.continually(), which seems to be infinite. It's important that the expression should not be evaluated until next() is called on the Iterator.

Is there a way to get this behaviour?

for example:

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 is usually combined with takeWhile:

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

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

Which prints:

eval 1
1
eval 2
2
eval 3

So if the condition that determines whether the computation should continue can be evaluated outside the computation then this works pretty well.

Basically I guess I'm saying Iterator.continually(getNext()).takeWhile(_ != certainValue) will achieve what you're trying to do. It's lazily evaluated.

这篇关于如何创建一个内容是表达式结果的有限迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆