Quick Tip : Streams in Scala

There are cases where one has to use the first n numbers of an infinite sequence
of numbers (like the Fibonacci numbers for example) but, unfortunately, there is
no way to determine how many members of the sequence will be actually needed.

Scala offers an better solution for the same – the ability to define infinite sized data structures  whose elements are computed on demand.These data structures are called streams. A stream is a list whose elements are not computed eagerly, but rather lazily. Eager evaluation means that a function first evaluates its arguments and then it uses them, while lazy evaluation means that an argument is evaluated only when it is needed.

Streams are created using the constant empty and the constructor cons, which are
both defined in module scala.Stream. For example, the following expression constructs a stream with elements 1 and 2:

Stream.cons(1, Stream.cons(2, Stream.empty))

Let us take an simple example :


This code can be used to create such a stream:

def numsFrom (n :Int):Stream[Int]  = Stream.cons(n,numsFrom (n+1))

Now we can create an “infinite” stream using the following command:

lazy val N = numsFrom(0)

The keyword lazy designates that the value assigned to the constant N should not
be evaluated. Now for the following expression

N take 10 print

Your output would be :

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, empty

Let us take another simple example. Suppose we want to print the number “10”  for desired times then using stream this can be written as :

Screenshot from 2013-01-11 10:31:24

You Can Read More on Streams here Computation with Streams

About Neelkanth Sachdeva

Project Manager @ eCIFM Solutions Inc. Previous : Senior Software Engineer @ Evernym Inc. Previous : Software Consultant @ Knoldus Software LLP Software Consultant @ Inphina Technologies
This entry was posted in Scala, Web. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s