Scala
I recently learned about Scala, a language for the JVM which tries to smoothly integrate object oriented and functional programming features.
I find it particularly interesting because of two reasons: first it is integrated with the Java platform and thus can use all the Java code already available. Second, it can be used almost as a Java evolution where you can gradually add functional concepts and more advanced features of the type system.
Scala is a static language, and lately the whole world is excited about dynamic languages, so this might seem a bit backwards, but I think sane static languages have their place in the world. And Scala has some very nice features (pattern matching on objects, flexible syntax) to make it appealing to me. I’d like to try to use it at work, integrating it with the bulk of Java code we already have.
To experiment a bit with the language I tried translating some examples from Haskell. The result is kinda pointless and probably not a good example of Scala programming, but it helped me get a feeling of the language.
package test.sort
object QuickSort {
def qsort1[A <% Ordered[A]](xs: List[A]): List[A] = xs match {
case y :: ys => {
val lt = for (val i <- ys; i < y) yield i;
val gt = for (val i <- ys; i >= y) yield i;
qsort1(lt) ::: List(y) ::: qsort1(gt)
}
case Nil => Nil
}
def qsort2[A <% Ordered[A]](xs: List[A]): List[A] = xs match {
case Nil => Nil
case z :: zs => {
def part(z: A, zs: List[A], parts: Tuple3[List[A], List[A], List[A]]): Tuple3[List[A], List[A], List[A]] = zs match {
case Nil => parts
case y :: ys => {
if (y > z)
part(z, ys, {parts._1, parts._2, y :: parts._3})
else if (y < z)
part(z, ys, {y :: parts._1, parts._2, parts._3})
else
part(z, ys, {parts._1, y :: parts._2, parts._3})
}
}
val parts = part(z, zs, Tuple3(Nil, List(z), Nil))
qsort2(parts._1) ::: parts._2 ::: qsort2(parts._3)
}
}
def qsort3[A <% Ordered[A]](xs: List[A]): List[A] = {
def qsort3b(ys: List[A], acc: List[A]): List[A] = ys match {
case Nil => acc
case List(z) => z :: acc
case z :: zs => {
def part(ps: List[A], parts: Tuple3[List[A], List[A], List[A]]): List[A] = ps match {
case Nil => qsort3b(parts._1, parts._2 ::: qsort3b(parts._3, acc))
case z :: zs => {
if (z > ys.head)
part(zs, {parts._1, parts._2, z :: parts._3})
else if (z < ys.head)
part(zs, {z :: parts._1, parts._2, parts._3})
else
part(zs, {parts._1, z :: parts._2, parts._3})
}
}
part(zs, {Nil, List(z), Nil})
}
}
qsort3b(xs, Nil)
}
}
