Skip to content
Browse files

add method dequeueOption to immutable.Queue

This allows immutable.Queue to be used conveniently in functional code.
Method is in the spirit of `headOption` on seqs or `get` on maps. Also
adds a unit test for immutable.Queue.
  • Loading branch information...
1 parent 636307b commit 58eadc09527c2b6722ddd830c0d3f319f2967ef7 @ziggystar ziggystar committed
Showing with 35 additions and 0 deletions.
  1. +7 −0 src/library/scala/collection/immutable/Queue.scala
  2. +28 −0 test/junit/scala/collection/QueueTest.scala
View
7 src/library/scala/collection/immutable/Queue.scala
@@ -118,6 +118,13 @@ class Queue[+A] protected(protected val in: List[A], protected val out: List[A])
case x :: xs => (x, new Queue(in, xs))
case _ => throw new NoSuchElementException("dequeue on empty queue")
}
+
+ /** Optionally retrieves the first element and a queue of the remaining elements.
+ *
+ * @return A tuple of the first element of the queue, and a new queue with this element removed.
+ * If the queue is empty, `None` is returned.
+ */
+ def dequeueOption: Option[(A, Queue[A])] = if(isEmpty) None else Some(dequeue)
/** Returns the first element in the queue, or throws an error if there
* is no element contained in the queue.
View
28 test/junit/scala/collection/QueueTest.scala
@@ -0,0 +1,28 @@
+package scala.collection.immutable
+
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+import org.junit.Test
+
+@RunWith(classOf[JUnit4])
+/* Tests for collection.immutable.Queue */
+class QueueTest {
+ val emptyQueue = Queue.empty[Int]
+ val oneAdded = emptyQueue.enqueue(1)
+ val threeAdded = emptyQueue.enqueue(1 to 3)
+
+ @Test
+ def dequeueOptionOnEmpty() {
+ assert( emptyQueue.dequeueOption == None )
+ }
+
+ @Test
+ def dequeueOptionOneAdded() {
+ assert( oneAdded.dequeueOption == Some((1,emptyQueue)) )
+ }
+
+ @Test
+ def dequeueOptionThreeAdded() {
+ assert( threeAdded.dequeueOption == Some((1,Queue(2 to 3:_*))) )
+ }
+}

0 comments on commit 58eadc0

Please sign in to comment.
Something went wrong with that request. Please try again.