May a while loop be used with yield in scala

前端 未结 3 856
梦毁少年i
梦毁少年i 2021-02-04 06:22

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 someThi         


        
相关标签:
3条回答
  • 2021-02-04 06:54

    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)
    
    0 讨论(0)
  • 2021-02-04 07:01

    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.

    0 讨论(0)
  • 2021-02-04 07:01

    Another way similar to suggestion by @rexkerr:

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

    This feels a bit more natural than the Iterator.continually

    0 讨论(0)
提交回复
热议问题