简体   繁体   中英

best practice to use scala immutable 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.

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.

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

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