My mostly technical blog. An on-line journal of my activity in the IT industry and any other technical interests or techy things that happen to catch my attention.

Monday, 19 January 2009

Scala, insertion sort and pattern matching

This posting shows insertion sorting in Scala. Insertion sort is not a particularly efficient algorithm but this example code does demonstrate the use of pattern matching on lists using the match keyword and the case x :: y type expression.

val result = values match {

case List() => List()

case value :: valuesTail => insert(value, iSort(valuesTail))}

The above code pattern matched the List values against 2 cases. The first being the empty list, in which case an empty list List() is returned. the second is the pattern value :: valuesTail, which puts the head of the list in value and the tail (the rest of the list) in valuesTail.

Example code:

package test

// Nb: This is not an efficient sorting algorithm but it domostrates// some aspects of scala for representing algorithms, along with functions as first class objects and curryingobject SortingTest {