Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best practice to use scala immutable Queue

Tags:

scala

queue

I would like to know how to use Queue in the best functional way. For example, I would like to dequeue elements and print them with a recursive function. And I would like the most beautiful function.

For example, this is a function doing what I want. But I dislike the if.

Is their a better way to use Queue ?

import scala.collection.immutable.Queue

def printQ[A](p:Queue[A]) {
  if(!p.isEmpty) {
    p.dequeue match { 
      case (x,xs) => 
        println(x.toString) 
        printQ(xs) 
      case _ => 
        println("End")    
    }
  }    
}

printQ(Queue(1,2,4,5))

Thanks for responses.

like image 631
fsart Avatar asked Apr 05 '12 10:04

fsart


2 Answers

Queue doesn't have a dequeueOption method, which would make it somewhat nicer. However, note that the first entry in your match is exhaustive; you cannot ever reach the println("End") code. So you could improve your version:

def printQ[A](p: Queue[A]) {
  if (!p.isEmpty) p.dequeue match {
    case (x,xs) =>
      println(x.toString)
      printQ(xs)
  }
}

Of course, since this just traverses the queue in order, one can always just

p.foreach(println)

to print everything out.

like image 142
Rex Kerr Avatar answered Oct 30 '22 16:10

Rex Kerr


You don't need to test for case _:

scala> @annotation.tailrec def printQ[A](p:Queue[A]) {
     |   if(!p.isEmpty) {
     |     p.dequeue match {
     |       case (x,xs) =>
     |         println(x.toString)
     |         printQ(xs)
     |     }
     |   }
     | }
printQ: [A](p: scala.collection.immutable.Queue[A])Unit

scala> printQ(Queue(1,2,4,5))
1
2
4
5

Is it necessary for function to be recursive?

scala> for (i <- Queue(1, 2, 4, 5)) println(i)
1
2
4
5
like image 41
senia Avatar answered Oct 30 '22 16:10

senia