diff options
author | Thomas Geier <thomas.geier@uni-ulm.de> | 2013-12-05 16:45:26 +0100 |
---|---|---|
committer | Thomas Geier <thomas.geier@uni-ulm.de> | 2013-12-05 17:00:05 +0100 |
commit | 58eadc09527c2b6722ddd830c0d3f319f2967ef7 (patch) | |
tree | 52b9bc2f2b4d276f2afe17c3da63c213da9d12f8 | |
parent | 636307b9ba35e856f34684cce8620983aa1ba702 (diff) | |
download | scala-58eadc09527c2b6722ddd830c0d3f319f2967ef7.tar.gz scala-58eadc09527c2b6722ddd830c0d3f319f2967ef7.tar.bz2 scala-58eadc09527c2b6722ddd830c0d3f319f2967ef7.zip |
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.
-rw-r--r-- | src/library/scala/collection/immutable/Queue.scala | 7 | ||||
-rw-r--r-- | test/junit/scala/collection/QueueTest.scala | 28 |
2 files changed, 35 insertions, 0 deletions
diff --git a/src/library/scala/collection/immutable/Queue.scala b/src/library/scala/collection/immutable/Queue.scala index 05c5dd799d..df1484c4ab 100644 --- a/src/library/scala/collection/immutable/Queue.scala +++ b/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. diff --git a/test/junit/scala/collection/QueueTest.scala b/test/junit/scala/collection/QueueTest.scala new file mode 100644 index 0000000000..9a40d8fc90 --- /dev/null +++ b/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:_*))) ) + } +} |