Beautiful Scala

This is, of course, beautiful:

def msort[T](less: (T, T) => Boolean)
      (xs: List[T]): List[T] = {
    def merge(xs: List[T], ys: List[T]): List[T] =
      (xs, ys) match {
        case (Nil, _) => ys
        case (_, Nil) => xs
        case (x :: xs1, y :: ys1) =>
          if (less(x, y)) x :: merge(xs1, ys)
          else y :: merge(xs, ys1)
    val n = xs.length / 2
    if (n == 0) xs
    else {
      val (ys, zs) = xs splitAt n
      merge(msort(less)(ys), msort(less)(zs))

scala> val intSort = msort((x: Int, y: Int) => x < y) _
intSort: (List[Int]) => List[Int] = <function1>
scala> intSort(List(3, 5, 1, 6, 2))
res3: List[Int] = List(1, 2, 3, 5, 6)

This is an example of a recursive merge sort implemented using a technique known as currying, expressed in the language Scala.

Some context: I was looking for a Java-based scripting language to act as 'glue' for my Java interface to OziExplorer which I'm using for a fenceline survey I'm doing for the Moors For The Future project. I initially looked at Groovy and came across an intriguing comment by James Strachan, the creator of Groovy:

I can honestly say if someone had shown me the Programming in Scala book by by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy.

That set me off on an exploration of the Scala website which has lots of good tutorials and links, including one to an online interpreter you can type examples into. Scala is a really intriguing language - it sits on top of the JVM so you get 'for free' Java's cross-platform support and access to the huge Java ecosystem, but Scala also blends together the features of some of the most influential languages that preceded it:

  • The 'everything is an object' nature of Smalltalk or Ruby
  • The imperative nature of languages that have C or Java heritage
  • Functional programming as per ML or Haskell
  • Strongly typed but with sophisticated type inferencing that makes it look & feel similar to Python or Groovy
  • Uniform access to methods and fields, like Eiffel
  • Actor-based concurrency similar to Erlang

Scala also adds new features of its own as well, such as abstract types, traits and extractors. It's also very easy to write domain-specific languages in Scala. James Strachan wrote a good summary of Scala, from which the above quote is taken.

I also ordered a copy of Programming in Scala, Second Edition which I'm enjoying reading and can thoroughly recommend. Unlike many programming books it's well written with a light but not overly-chatty style. It explicitly assumes you have programming experience, so it picks up pace pretty quickly. As I've been going through the book, most of my "Why did they do that?" questions have had good answers, which gives the impression that Scala has been very carefully thought through - always a good sign.

Now all I have to do is to think of a substantial project I can use Scala on :-)

Tags : ,
Categories : Tech, Scala