可以在scala中使用一会儿循环并产生收益 [英] May a while loop be used with yield in scala

查看:76
本文介绍了可以在scala中使用一会儿循环并产生收益的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是scala中for/yield的标准格式:请注意,它需要一个集合-其元素驱动迭代.

Here is the standard format for a for/yield in scala: notice it expects a collection - whose elements drive the iteration.

for (blah <- blahs) yield someThingDependentOnBlah

我有一种情况,循环中会出现不确定的迭代次数.内部循环逻辑确定将执行多少次.

I have a situation where an indeterminate number of iterations will occur in a loop. The inner loop logic determines how many will be executed.

while (condition) { some logic that affects the triggering condition } yield blah

每次迭代都将生成序列的一个元素-就像编写了yield一样.推荐的方法是什么?

Each iteration will generate one element of a sequence - just like a yield is programmed to do. What is a recommended way to do this?

推荐答案

您可以

Iterator.continually{ some logic; blah }.takeWhile(condition)

得到几乎相同的东西.您需要使用一些可变的(例如var)逻辑来影响条件.否则可以

to get pretty much the same thing. You'll need to use something mutable (e.g. a var) for the logic to impact the condition. Otherwise you can

Iterator.iterate((blah, whatever)){ case (_,w) => (blah, some logic on w) }.
         takeWhile(condition on _._2).
         map(_._1)

这篇关于可以在scala中使用一会儿循环并产生收益的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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