Scala infatuation

16 Mar 2008

Why my recent infatuation with scala? (Actually, since it’s reaching a half year, I guess it can no longer be called an infatuation.) Here’s my answer in the form of a quick example. I want to determine the average of a list of timings for something.

In python:

timings = [1.2, 1.5, 1.3, 1.5]
reduce(lambda a, b: a + b, timings, 0.0) / len(timings)

In ruby:

timings = [1.2, 1.5, 1.3, 1.5]
timings.inject(0.0) { |a, b| a + b } / timings.length

Besides demonstrating that ruby is just python with different spelling, this shows they both have some powerful built-in functions and syntax. I can type one line for calculating the average and move on to the real point of my code, whatever that is.

Here it is in scala:

var timings = Array(1.2, 1.5, 1.3, 1.5)
timings.foldLeft(0.0) { (a, b) => a + b } / timings.size

It’s pretty much the same! I can type code that is very close to the pseudocode in my head, and move on.

Whether intentionally or not, scala is borrowing very heavily from the “high level” language features of python (and ruby). But it’s running on top of the JVM, which is still the best combination of interpreter machine + libraries out there. Python’s VM is amateur at best, and ruby’s is even worse. This way is like getting my reeces cup, two great tastes that taste great together: a high-level, pseudocode language on top of a racecar engine.

I suspect this is the main reason scala has been getting a lot of attention recently, in spite of the gaping lack of decent documentation or tools.

Oh yeah, here’s that same code in java. I’m not including the creation of the array, because that takes 5 lines all by itself, and wouldn’t be fair to compare:

// assume omitted var: List<Double> timings.
double sum = 0.0;
for (double d : timings) {
    sum += d;
double average = sum / timings.size();

For java versions before 1.5, it’s a lot worse.

Incidentally, last night I found a nice introductory article on scala, which I skimmed and recommend.

« Back to article list

Please do not post this article to Hacker News.

Permission to scrape this site or any of its content, for any purpose, is denied, regardless of your personal beliefs or desire to design a novel opt-out method.