Recursive Streams and collection in Scala
Last Updated :
25 Apr, 2023
Recursive forms have their definition in terms of themselves like we have subfolders in folders which can further have subfolders. Recursive methods calling themselves is also a recursive form. Similar forms can be used to create a recursive stream. Example 1: Creating a lazy list
scala
object Geeks
{
def main(args : Array[String])
{
lazy val geek = Stream.cons( 1 , Stream.cons( 5 , Stream.empty))
println (geek)
(geek take 4 ) foreach {
x = > println(x)
}
}
}
|
Output :
Stream(1, ?)
1
5
In the code above the second con can be recursive. Example 2: Create a lazy list by placing a recursive call to method
scala
object Geeks
{
def main(args : Array[String])
{
def geek(n : Int) : Stream[Int] = Stream.cons(n, geek(n+ 1 ))
lazy val q = geek( 5 )
println(q)
}
}
|
Output :
Stream(5, ?)
Example 3: Create a lazy list by placing a recursive call to method in a brief and clear manner
scala
object Geeks
{
def main(args : Array[String])
{
def geek(n : Int) : Stream[Int] = n #:: geek(n+ 1 )
lazy val q = geek( 5 )
println(q)
}
}
|
Output :
Stream(5, ?)
Stream Collections
Stream collections in scala are very important as it allows need not to be explicitly lopped over. Declaratively things can be performed using functional combinators like map, filter, and flatMap. Streams are lazy lost collections. Example 4:
scala
object Geeks
{
def main(args : Array[String])
{
def geek(n : Int) : Stream[Int] = n #:: geek(n+ 1 )
lazy val g = geek( 0 )
println (g)
println (g.take( 10 ).mkString(" ; "))
}
}
|
Output :
Stream(0, ?)
0 ; 1 ; 2 ; 3 ; 4 ; 5 ; 6 ; 7 ; 8 ; 9)
Example 5: Using filter
scala
object Geeks
{
def main(args : Array[String])
{
val geek = List( 1 , 2 , 3 , 4 )
val abc = geek filter { x = > x > 2 }
println(abc)
}
}
|
Output :
List(3, 4)
filter is called over the list geek. It takes function as an argument and returns a Boolean, which is a function predicate. Every element is run through the function and elements are filtered out where the function returns false. It results in a new list and the original “geek” list is remain persistent. Example 6: Using filter in a much concise manner
scala
object Geeks
{
def main(args : Array[String])
{
val geek = List( 1 , 2 , 3 , 4 )
val abc = geek filter { _ > 2 }
println(abc)
}
}
|
Output :
List(3, 4)
In the code above, there is no need to name the element. The element is referred by a shorter form via a_. Also there is no need to qualify the method call.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...