如何从scala中的for循环产生单个元素? [英] How to yield a single element from for loop in scala?

查看:33
本文介绍了如何从scala中的for循环产生单个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很像这个问题:

提前退出循环的函数代码

说代码是

def findFirst[T](objects: List[T]):T = {
  for (obj <- objects) {
    if (expensiveFunc(obj) != null) return /*???*/ Some(obj)
  }
  None
}

如何在 Scala 中从这样的 for 循环中生成单个元素?

How to yield a single element from a for loop like this in scala?

我不想使用原始问题中提出的 find ,我很好奇是否以及如何使用 for 循环来实现它.

I do not want to use find, as proposed in the original question, i am curious about if and how it could be implemented using the for loop.

* 更新 *

首先,感谢所有评论,但我想我在问题中不清楚.我正在拍摄这样的东西:

First, thanks for all the comments, but i guess i was not clear in the question. I am shooting for something like this:

val seven = for {
    x <- 1 to 10
    if x == 7
} return x

这不能编译.这两个错误是:- 返回外部方法定义- 方法 main 有返回语句;需要结果类型

And that does not compile. The two errors are: - return outside method definition - method main has return statement; needs result type

我知道 find() 在这种情况下会更好,我只是在学习和探索这门语言.在有多个迭代器的更复杂的情况下,我认为使用 for 查找实际上很有用.

I know find() would be better in this case, i am just learning and exploring the language. And in a more complex case with several iterators, i think finding with for can actually be usefull.

感谢评论者,我将开始悬赏以弥补问题的不当之处:)

Thanks commenters, i'll start a bounty to make up for the bad posing of the question :)

推荐答案

您可以将列表转换为流,以便 for 循环包含的任何过滤器仅根据需要进行评估.但是,从流中产生总是会返回一个流,而您想要的是我假设一个选项,因此,作为最后一步,您可以检查生成的流是否至少有一个元素,并将其头部作为选项返回.headOption 函数正是这样做的.

You can turn your list into a stream, so that any filters that the for-loop contains are only evaluated on-demand. However, yielding from the stream will always return a stream, and what you want is I suppose an option, so, as a final step you can check whether the resulting stream has at least one element, and return its head as a option. The headOption function does exactly that.

def findFirst[T](objects: List[T], expensiveFunc: T => Boolean): Option[T] =
    (for (obj <- objects.toStream if expensiveFunc(obj)) yield obj).headOption

这篇关于如何从scala中的for循环产生单个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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