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.
Queuedoesn’t have adequeueOptionmethod, which would make it somewhat nicer. However, note that the first entry in your match is exhaustive; you cannot ever reach theprintln("End")code. So you could improve your version:Of course, since this just traverses the queue in order, one can always just
to print everything out.