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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With