How to match pattern with scala immutable queue?

I want to use immutable.Queueand in particular

  • I want to access the head of the queue without distracting her. An 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?

+4
source share
1 answer

You can use the universal layout +:on Seq:

val q = Queue.empty[Int]

q match {
  case x +: xs => // non-empty case
  case _ => // empty case
}

Queue unapplySeq:

q match {
  case Queue(x, _*) => // non-empty case
  case Queue() => // empty case
}

, , Queue.head, , O(1) .

+7

All Articles