Friday, May 27, 2011

Beautiful example of Scala code

This is directly from the "Programming in Scala" book, but it illustrates the language so well.

In calculating the greatest common divider, or gcd, one can write code like that

def gcd(x: Long, y: Long): Long =
  if (y == 0) x else gcd(y, x % y)


and the beauty of it is in looking exactly as the mathematical formula from which the algorithm is derived.

HOWEVER

The biggest claim against Scala programmers, and possibly against newbie Scala programmers (like myself), is that they take the best Scala example and match it against the worst Java code. So, to be fair, here is the same code in Java:

public long gcd(long x, long y) {
  if (y == 0) return x; else return gcd(y, x % y);
}


Is it that much different? Perhaps not, and all we achieved is give an example of things to come. Scala is closer to a mathematical formula, but so far that's it. Well, as everyone knows, the biggest advantage is that in Scala semicolon; is optional!

Art: William-Adolphe Bouguereau : La leçon difficile (The difficult lesson)

No comments: