Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

May a while loop be used with yield in scala

Tags:

yield

scala

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?

like image 607
WestCoastProjects Avatar asked Oct 25 '14 00:10

WestCoastProjects


People also ask

What is yield in for loop Scala?

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.

How does for yield work in Scala?

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.

Why yield is used in Scala?

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.

What is while loop in Scala?

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.


2 Answers

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)
like image 191
Rex Kerr Avatar answered Oct 27 '22 02:10

Rex Kerr


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.

like image 36
Daniel C. Sobral Avatar answered Oct 27 '22 01:10

Daniel C. Sobral