Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How am I *supposed* to use a scala.collection.immutable.Queue?

Tags:

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.

  1. My first instinct was 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.
  2. I cannot figure out the syntax for a 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 ...

like image 605
Michael Lorton Avatar asked Dec 27 '10 20:12

Michael Lorton


People also ask

What is queue collection in Scala?

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.


1 Answers

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 qith 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).

like image 180
Rex Kerr Avatar answered Oct 10 '22 19:10

Rex Kerr