2008-04-25

Scala: functional programming for Java

Programming is a long and complex effort for projects of any size and consequently we are in a constant quest to find a language to improve productivity: deliver quality results using less time and effort.

I have no statistics about distribution of programming language usage. A thesis is that Java enjoys a lead among languages in use today: Internet, Web Services, finance, telecoms, health, communications, aviation, military, automobile, oil, factory automation, appliances and consumer products, etc.

The topic of alternate languages to Java often brings lively discussions of pros and cons among languages such as Ruby, Groovy, Python, Erlang, Scala, F#, C#, Lisp, PHP, C++, C and JavaScript among several others.


After some reading and limited experimentation with these alternate languages, I come to the conclusion, thesis without proof, that Java is here to stay in the lead. However, Scala profiles as a language that leverages and expands the Java experience, and JVM, and may contribute to an even greater use of Java through Scala.

Scala is a relatively new language; some basic points about Scala include the following:

  • Created. Created by Martin Odersky at L'École Polytechnique Fédérale de Lausanne in 2001.
  • Platform. Runs on the Java Virtual Machine, JVM, and directly uses and produces Java classes, Java byte-code. An implementation for MS .NET is available but appears less developed.
  • Features. The main distinguishing factor of Scala is its support for both object and functional programming models.
  • Object-oriented language. All entities are typed objects. Types are defined by Classes and Traits constructs that offer flexibility in defining class hierarchies.
  • Functional-oriented language. Scala's object orientation mixes with a well defined pattern-based approach to declare what is to be done rather than how; functional versus imperative approach to define algorithms. Erlang is the functional language often mentioned when describing Scala's functional features.
The following points summarize few days experimenting with Scala.

Pros
  • Java. Scala is a natural language progression for Java programmers. Existing libraries can be reused and classes developed with Scala can be incorporated and used in Java.
  • JVM. Scala uses the well tested and cross platform Java Virtual Machine, JVM.
  • Object-oriented. Classes and Traits are designed in a manner that allows flexibility in defining class structures.
  • Typed language. Scala infers type permitting concise expressions, typical of dynamically-typed languages, while type enforcement is done at compile time. Dynamically-typed languages do not require variables to be declared as a specific type; any variable can contain any value or object. Dynamically-typed languages offer great flexibility and concise statements at the expense of undetected potential errors. Scala offers expression conciseness of dynamically-typed languages while the compiler infers and strictly enforces type conformity.
  • Functional-oriented. Scala has an algebraic foundation that as one becomes familiar with it helps understand the less intuitive aspects of the language. Pattern matching and support for higher-order functions, methods accepting functions as parameters, are among the powerful functional features. Thread management under the Actors library appears as a native language feature to the end-user, the programmer.
Cons
  • Scala is new. Although introduced in 2001, Scala has just recently received wider attention. Programmers, students and the rest of us will need much more time to learn, understand and use Scala.
  • Acceptance. Time will tell how Sun, Google, IBM, industry, the Internet and the IT communities accept Scala. A good sign of acceptance would be Google deploying a Scala API for the recently introduced Google Application Engine, which offers a Python only implementation now.
Included below is a quick-sort method as shown in Scala by Example.
  • Application. Defines SortTest as a console application.
  • Method sort. Defines method sort that takes a list of integers, xs, and returns, results is what Scala calls it, in a list of integers, def sort(xs: List[int]): List[int] =
  • Check input list for length 1 or empty. The method results the input list, xs, should it be of length of 1 or less. return statement can be used; it is often unneeded in Scala.
  • Define pivot. Defines a val object assigned to the value of the element at position xs.length / 2 of the input list, xs. Scala differentiates between 'val' and 'var' objects; var objects can be modified; val objects are unmodifiable. Also note that the compiler infers the type for pivot as integer and enforces it. The statement as written appears from a dynamically-typed language since no type is stated. Note how pivot is defined, val pivot = xs(xs.length / 2); the inferenced statement is, val pivot: int = xs(xs.length / 2)meaning a val object of type integer, ': int', assigned the integer value at xs( xs.length / 2)
  • Sort recursively. Defines three sub-lists, less than, equal and greater than pivot, and catenates these lists using Scala's less than intuitive catenate operator ':::' The List object has a method, filter(), that takes a function expression, as shown in, xs.filter( x => x < pivot), and applies that function, x < pivot to all elements of the list, and results (returns) the elements that match the expression.
object SortTest extends Application {

def sort(xs: List[int]): List[int] = {
if (xs.length <= 1) xs
else {
val pivot = xs(xs.length / 2)
sort(xs.filter(x => x < pivot)) :::
xs.filter(x => x == pivot) :::
sort(xs.filter(x => x > pivot))
}
}

// now, define a List, Y, sort it and print
val Y = List(3, 4, 0, 7, 9, -8, 8, -3, 1)
Console.println( sort(Y) )
}

Compile and run as follows:
scalac SortTest.scala
scala SortTest
List(-8, -3, 0, 1, 3, 4, 7, 8, 9)
A second example serves also to show the power and conciseness of Scala. This example is found at the Scala site under the subject: A Tour of Scala: Automatic Type-Dependent Closure Construction.

Here we define a method, myWhileLoop, that takes two parameters, cond, of type function that results Boolean, and body also of type function that results Unit, and the method results an object of type Unit. Unit returns no value, like void in Java, but it represents zero or more lines of code, it is a unit of code. Once defined, the method is used as if myWhileLoop were native to the language or at least it looks so.

The combination of => refers not to equal and greater than characters, but used in Scala to designate a very useful object type, a function. A function type is represented by what is called in Scala a right-arrow; think of it as one symbol instead of two, possibly borrowed from math to denote a function: leads to, becomes, transforms from one equation to another.
object TargetTest1 extends Application {
def myWhileLoop(cond: => Boolean)
(body: => Unit ): Unit = {
if (cond) {
body
myWhileLoop(cond)(body)
}
}

// use 'myWhileLoop' as if defined in the language
var i = 0
myWhileLoop (i < 5) {
println(i); i += 1
}
}

Compile and run as follows:
scalac TargetTest1.scala
scala TargetTest1
0
1
2
3
4
Here is a third example extracted from the Scala site, A Tour of Scala: Mixin Class Composition. It shows the power of Scala to define class hierarchies via class, trait, abstract and with expressions.
abstract class AbsIterator {
type T
def hasNext: Boolean
def next: T
}

trait RichIterator extends AbsIterator {
def foreach(f: T => Unit) { while (hasNext) f(next) }
}

class StringIterator(s: String) extends AbsIterator {
type T = Char
private var i = 0
def hasNext = i < s.length()
def next = { val ch = s charAt i; i += 1; ch }
}

object StringIteratorTest {
def main(args: Array[String]) {
if ( args.length > 0 ) {
class Iter extends StringIterator(args(0))
with RichIterator
val iter = new Iter
iter.foreach(println)
}
}
}

Compile and run as follows:
fsc StringIteratorTest.scala
scala StringIteratorTest abc123
a
b
c
1
2
3