Posted in Scala

Scala Streams Examples

A couple of Scala streams examples for reference

Recursive Definition

The basic fibonacci example defines each element in the stream as the sum of the previous two elements in the stream.

def fibFrom(a: Int, b: Int): Stream[Int] = a #:: fibFrom(b, a + b)
val fibs = fibFrom(1,1)

Using From with Mapping or Filter

Use from for a basic sequence and then apply a mapping function on the sequence. The mapping function is evaluated lazily. In this case a stream of all squares.

Stream.from(1).map(x => x * x)

Mapping or Filter Function Recursively

A prime is defined as a number that is only divisible by 1 and itself (not including 1) and all numbers can be defined as a product of their primes. This gives an clean way of define the next prime as next integer that is not divisible by any of the previous primes in the stream. You can apply a filter function to the tail and its only evaluated lazily.

def primeStream(s: Stream[Int]): Stream[Int] = s.head #:: primeStream(s.tail filter(_ % s.head != 0))
val primes = primeStream(Stream.from(2))

Converting Java Readers to a Stream

This is a handy way to convert a Java style reading into Stream so it can be process with map and fold functions easily.

val reader: BufferedReader = ..
val lines = Stream.continually(reader.readLine()).takeWhile(_ != null)
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s