Just another WordPress.com site

Power of Scala

I recently attended a good presentation on Scala at the 2013 Silicon valley code camp.

Ramnivas Laddad, the speaker did an excellent job of covering some cool features

of Scala.

After the talk, I summed up some energy to solve a few Project Euler problems

with scala.

So Problem #2 is to find the sum of even Fibonacci numbers below 4 million.

What makes it a really interesting problem in Scala world is the streams features that

the language provides and how it can be used to craft a nifty solution.

// define a recursive infinte stream of fib numbers
def fibonacciStream(first: Int, second: Int) : Stream[Int] = {
second #:: fibonacciStream(second, first+second)}

// Filter stream to even numbers, take all below 4 million and add up the sequence
print(fibonacciStream(0,1).filter(_ % 2 == 0).takeWhile(_ <= 4000000).foldLeft(0)(_ + _))

This elegant piece of code shows the power of Scala’s functional programming. if you want to

learn more take a look at this blog -> Scala for Project Euler.

Checkout Scala for Java Developers.

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

%d bloggers like this: