February 11 2011

Scala

In an earlier post on Project Euler I mentioned that I was using the problems from the project as one way of picking up the language Scala.
Scala is quite interesting. It is a new language, but it utilizes the Java VM to run upon (Scala compiles to bytecode). This cool idea lets a programmer take advantage of the plethora of Java code that is already out there and call it quite easily from a Scala program.
Scala is object oriented, but more importantly (otherwise just use Java) Scala is a functional language. Every value is a object, and every function is a value. The syntax lets you do things in either a way that seems natural to someone who has been programming in Java (or C) or in a much more succinct functional style.
For example, the first problem in project Euler is to add all the natural numbers below one thousand that are multiples of 3 or 5.
A simple way of doing this in Java would be:

int accum = 0;

for (int i=1; i <= 1000; i++) { if ( i % 3 == 0 || i % 5 == 0) accum += i; } System.out.println(accum);
This is a pretty straightforward rendering of the problem.

In Scala we could do something like:

println( (1 until 1000).filter(n => n%3 == 0 || n%5 == 0).foldLeft(0)(_+_) )

This looks kind of odd on first glance, but it is really doing something similar to the java example.
(1 until 1000) defines the range of numbers from 1 to 1000. until is a method in this case, producing a Range. The filter method is then called, on that Range instance and selects all of the elements that satisfy the predicate (n%3 == 0 || n%5== 0) or in other words, all the elements that are divisible by 3 or 5. On this new Range, we then call foldLeft. This takes a starting value of 0 and applies the function "+" to successive elements (remember + is a value too). The result is then printed.
In this example, the Java code was pretty simple, so the advantage of using Scala may not be immediately apparent. It is kind of fun though. I'll share a more complex example later.



Copyright 2019. All rights reserved.

Posted February 11, 2011 by user in category "Computation

Leave a Reply

Your email address will not be published. Required fields are marked *