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?
yield keyword will returns a result after completing of loop iterations. The for loop used buffer internally to store iterated result and when finishing all iterations it yields the ultimate result from that buffer.
Summary: Scala's 'yield' keywordFor each iteration of your for loop, yield generates a value which is remembered by the for loop (behind the scenes, like a buffer). When your for loop finishes running, it returns a collection of all these yielded values.
Yield is a keyword in scala that is used at the end of the loop. We can perform any operation on the collection elements by using this for instance if we want to increment the value of collection by one. This will return us to the new collection.
Advertisements. Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. A while loop statement repeatedly executes a target statement as long as a given condition is true.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With