May a while loop be used with yield in scala

主宰稳场 提交于 2019-12-03 11:58:38

问题


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

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?


回答1:


You can

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

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)



回答2:


Using for comprehensions is the wrong thing for that. What you describe is generally done by unfold, though that method is not present in Scala's standard library. You can find it in Scalaz, though.




回答3:


Another way similar to suggestion by @rexkerr:

 blahs.toIterator.map{ do something }.takeWhile(condition)

This feels a bit more natural than the Iterator.continually



来源:https://stackoverflow.com/questions/26558120/may-a-while-loop-be-used-with-yield-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!