Best practices for using scala immutable queues

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

For example, this is a function that does what I want. But I do not like it if.

Is their the best way to use the 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 answers.

+6
source share
2 answers

Queue does not have a dequeueOption method, which would make it a little nicer. However, note that the first record in your match is exhaustive; you can never reach the println("End") code. This way you can 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 it just moves the queue in turn, you can always just

 p.foreach(println) 

to print everything.

+3
source

You do not need to test 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 

Does it need to be recursive for a function?

 scala> for (i <- Queue(1, 2, 4, 5)) println(i) 1 2 4 5 
+2
source

Source: https://habr.com/ru/post/912485/


All Articles