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.
Leave a Reply