I have what I would think is the most common case for processing a queue. I will read off the front of the queue, act on the element (which may cause more elements to be added to the queue), and then loop until the queue is empty.
foreach
, but no, apparently a queue (even a mutable one) is strict and the foreach loops over all the elements that are in the queue when the iteration starts.while
loop.You'd think that it would be something like
while (!q.isEmpty) { var (e, q) = q.dequeue ... }
would work, except that I'm redeclaring q
. This does work:
while (!q.isEmpty) { var (e, q1) = q.dequeue q = q1 ... }
but man, does it look wrong ...
In Scala, Queue is implemented as a pair of lists. One is used to insert the elements and second to contain deleted elements. Elements are added to the first list and removed from the second list. The two most basic operations of Queue are Enqueue and Dequeue.
Here's one way to avoid any vars at all:
val q0 = collection.immutable.Queue("1","Two","iii") Iterator.iterate(q0) { qi => val (e,q) = qi.dequeue println("I just dequeued "+e) // Your side-effecting operations go here if (e.length!=2) q.enqueue("..") // Your changes to the queue go here else q }.takeWhile(! _.isEmpty).foreach(identity)
You start with the initial queue, q0
, and then on the qi
th step, you dequeue something and produce a new queue if need be, returning that for the next step.
All you have left is the stopping condition (not empty), and then since this just defines a process, not the actual action, you have to run it (using a no-op foreach, for example).
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