简体   繁体   中英

How to pattern match a scala immutable queue?

I want to use immutable.Queue and in particular

  1. 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?

  2. I like the pattern matching syntax for List (eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM