I want to use immutable.Queue
and in particular
I want to access the head of the queue without dequeuing it. Immutable queue is implemented using two immutable lists/stacks, and from the code it looks like this operation is not constant time (see this line), although dequeue is (amortized constant time). Can someone confirm or correct me?
I like the pattern matching syntax for List
(e.g., list match { case head :: tail => ... }
). Do we have something similar for Queue
as well?
You can use the general purpose matcher +:
on Seq
:
val q = Queue.empty[Int]
q match {
case x +: xs => // non-empty case
case _ => // empty case
}
You can also use Queue
's unapplySeq
:
q match {
case Queue(x, _*) => // non-empty case
case Queue() => // empty case
}
Note that both of these are potentially more inefficient than Queue.head
, since they have to construct the dequeued Queue as well, which is only O(1)
in amortized time.
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