18 October 2009

Programming Scala: Wampler & Payne

Programming Scala is a near-perfect O'Reilly book on Scala.

Explanations are clear and the right length.

The downloadable code examples include a build and test step that demonstrates the care and consideration of the authors to getting it right for the readers.

in reference to: Amazon.com: Programming Scala (Animal Guide) (9780596155957): Dean Wampler, Alex Payne: Books (view on Google Sidewiki)

05 July 2009

Scala Koala: I'm a solitary main()

Scala main() must be in a standalone object by itself?

I was a bit surprised by this:

java.lang.NoSuchMethodException: HelloWorld.main([Ljava.lang.String;)

I thought I'd seen numerous examples in books and on the web of classes and objects defined with the same name in the same Scala source file. And I have!

So I thought I'd begin my nascent Scala library in a single file, with a main() driver function:

class STable {
val cols = List()
val rows = List()
}

object STable {
def main(args: Array[String]) {
val table = new STable()
}
}


Steps Book Says

On page 68 of Programming In Scala it says: To run a Scala program, you must supply the name of a standalone singleton object with a main method that takes one parameter, an Array[String], and has a result type of Unit.

Am I The Only One?

Others have struck the same problem:
  • John Tyler in his Nable post expresses a healthy response to the unexpected
  • And Wondering Around's Scala's main issue post is a little annoyed but positive about Scala

Bug or Feature?

I was relieved to find that it's actually a bug. Possibly edging its way into being a feature if it isn't fixed.

It's Scala Ticket #363 which is a reopened defect.

Bill Venners got it right for the book:

In which case I need to update the book because it is wrong. It should
say that any *standalone object* with a main of the proper signature
can be used as an entry point into an application. MyApp$ has a main
method, but it isn't static. I had never attempted to make an
application with anything other than a standalone object.

The book reflects the current reality.

I look forward to this defect being fixed so it doesn't catch the unwary unawares.

17 February 2009

Scala parsing JSON with scala.util.parsing.json

What I'm Trying To Do

I'm converting our internal corporate data format AXF into JSON and XML so we can publish some of our data on the web.

I don't expect that the AXF to JSON conversion would be of much interest outside my organisation. It suffices to say that it was written in C, and that it is completely general: Any AXF data file can be converted to JSON.

From past experience, it's non-trivial converting from AXF to XML. My thinking is to go from AXF to JSON (easy), and from JSON to XML (hopefully fairly easy).

Two JSON Formats

Forgive me if I'm repeating something that's already well known. There was a requirement from internal developers that the JSON be as compact as possible. To achieve that, I generate JSON in two formats:
  1. Row-major order
  2. Column-major order
Row-major order is much easier for humans to read and comprehend: It's an array of objects.

Column-major order JSON is about half the size of row-major JSON, because the key names are used just once at the beginning of each array of a given data type, rather than within each object as is the case with row-major JSON.

The C based axf2json utility has a -r and -c options to switch between these JSON output styles.

JSON to Scala

Here's the code for reading and parsing a JSON file into Scala:





import scala.io.Source
import scala.util.parsing.json._

object Json2Xml {

def main(args: Array[String]) = {
val fname = "mydata.json"

// Read the JSON file into json variable.
var json: String = ""
for (line <- Source.fromFile(fname).getLines) json += line

// Get parse result Option object back from try/catch block.
val option = try {
JSON.parseFull(json)
} catch {
case ex: Exception => ex.printStackTrace() None
}

// See what we found.
option match {
case None => println("observations JSON invalid")
case Some(elements) => // Turn it into XML.
}

()
}




It would be nice to be able to make a single call to a function and get back the entire ASCII contents of a file. So far as I can see, there's no such function in Scala that does that. There is in Groovy. It would like to not need to loop through the file a line at a time.

11 January 2009

Rewire Your Brain with Functional Thinking

Rewire Your Brain
With your rewired brain you will begin to program in ways you have scarcely imagined.

Programmers often Musicians || Multi-Talented
If you are a good programmer, it's likely that you also have seemingly contrasting skills in music, sport, linguistics, dance, or have a warped sense of humour. You can see problems from more perspectives than the average bear.

Functional Programming: A Whole New Way of Thinking
Writing
recursive functions instead of while() loops requires a different way of thinking. Writing recursive functions in C or Java is relatively isolated within the overall scheme of things. It's not the whole program. It's not every while() and for() loop
re-implemented as a recursive function. And there's a tendency to mentally translate the recursive function into a procedural loop to understand it. It's like translating (say) French into English to understand it without bothering with the deep mental transformation and brain rewiring required to actually think in French. We need to think functionally.

Full Immersion in Functional Programming: Haskell etc.
While reading and working my way through Martin Odersky:
Programming In Scala I am often enough tempted to translate functional examples into procedure code. In fact, that's a valid teaching method employed in Programming In Scala to facilitate the transition of Java programmers from purely procedural and object-oriented programming, to functional programming. I don't think I need to learn multiple functional languages in order to master Scala, but it sure would help. Very often writers who are explaining and teaching Scala have a functional background, and it's easy for them to forget some of what it was like to not know functional programming. So, for my own benefit, I am immersing myself in Haskell to help me learn Scala. I am reading Real World Haskell and working through the exercises and examples.

Haskell Goes Back a Long Way
Haskell has a long history and was designed by committee to consolidate a range of functional languages that were splitting the functional community's focus and attention. There are numerous books available on Haskell such as the recently released O'Sullivan et al. Real World Haskell, and a much older book by Davie called 
Introduction to Functional Programming Systems Using Haskell. Davie's book is deep, while O'Sullivan's book is much gentler and up-to-date with the latest ghc Haskell compiler.

There will be some code in the next post!

28 December 2008

Hello World Scala


Why I Am Learning Scala

Multi-core processors are on the ascendancy. The programs you write will normally run in just one of the cores. To take advantage of the additional cores, you will need to write concurrent code. You can do that in Java, but it's a challenge. There is the ever-present possibility of deadlock and race conditions sneaking past your tests.

Functional languages (such as Scala) have an advantage over non-functional languages (such as Java) when writing concurrent programs. A key advantage of functional languages is that they facilitate immutable object state. The fields of an immutable object cannot change underneath your feet and lead to hairy unpredictable behaviour. For instance, Java String objects are immutable. While my program is accessing a String object, I can rely on it remaining the same size and containing the same chars. If I take a substring of my String object, the substring returned is a different immutable String instance and the original String remains unscathed.

Scala
is a well-designed hybrid language which allows both Java-like imperative programming, and functional programming as with Haskell and Erlang. That means I don't have to jump straight into the functional deep end of the swimming pool. I can dip my toes into the water at the shallow end with Scala imperative programming while getting up to speed with functional programming.

Multi-core processors are not going to go away. Even if tomorrow there is a materials break-through and individual cores escape their current physical limits, a concurrent functional program will still have a huge performance advantage on multi-core processors built with the faster cores.

I cannot ignore the trend to multi-core processors. With each increase in the number of cores in a processor -- 2, 4, 8, 16, 32 -- the speed of a single-core process will stagnate at its current level. In fact, with the increased overhead of multi-core processors the usable performance of the individual cores may actually go down.

I decided on Scala for several reasons such as type safety, type inference, performance, closures, and access to all Java's class libraries.

My First Simple Scala main() Program
object HelloScala {
def main(args: Array[String]): Unit = println("Hello Scala!")
}

  1. Save the above three lines of code to a Scala source code file:

  2. HelloScala.scala

  3. Compile with the Scala compiler:

  4. scalac HelloScala.scala

  5. Run by invoking the Scala virtual machine:

  6. scala HelloScala
    Hello Scala!

It's Java Equivalent


class HelloJava {
public static void main(String args[]) {
System.out.println("Hello Java!");
}
}


  1. Save the above five lines of code to:
  2. HelloJava.java

  3. Compile with the Java compiler:

    javac HelloJava.java

  4. Run by invoking the Java virtual machine:
    java HelloJava
    Hello Java!

Further Reading

Followers