Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pattern match a scala immutable queue?

Tags:

scala

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 (e.g., list match { case head :: tail => ... }). Do we have something similar for Queue as well?

like image 491
user716468 Avatar asked Jun 05 '15 19:06

user716468


1 Answers

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.

like image 115
gzm0 Avatar answered Sep 18 '22 02:09

gzm0