Friday, March 28, 2008

Lorem Ipsum in Scala (or 'how Weiqi Gao took my Friday night')

"Gah!!!!", our hero grits his teeth and slams a hand on the keyboard, " Darn you, Weiqi Gao....".

It is late on a Friday night. Our hero has decided to give the dreaded Friday Scala Quiz a shot. Even though the challenge was clearly in jest, the temptation is just too great. Why not try? However, there is just one problem: despite attending several presentations on the language, he has only recently downloaded Scala, and tried only a simple HelloWorld program.

"What was that syntactic sugar for a method call?", he muses aloud, pouring another shot of gin into a tumbler filled with Red Bull. Whirling to the desk, he rifles through some notes from one of the presentations -- aha!

" obj.method(param) can be written as obj method param ! ", he cackles gleefully.

Hours later, with his head in his hands, he stares at the enigmatic error message from the sentient being that is the Scala type-inference engine. It mocks him. Miles away, Weiqi looks up from an abstract algebra textbook and smiles.

Some time later, the problem space is reduced considerably. The goal is now: a working Scala program that has the following, simple Latin phrase:

Lorem ipsum dolor sit amet , consectetur adipisicing elit. Ut enim
It contains some key ingredients: the comma, the period, and capitals. True, it does not contain an ending period, the word "do", or many of the other words.

Time passes.... Much is learned, or at least inferred, about Scala -- far more so than a "Hello World 2" program. And finally.... a modest success:

object Lorem {
def ipsum(x: Any) = this
def sit(x: Any) = println("Darn you, Weiqi!")
}

class Consectetur {
def adipisicing(x: Any) = this
def enim() = "It is late on a Friday"
}

class Elit {
def Ut() = this
}

object Runner {
def main(args: Array[String]) {
var dolor, sit, amet = null
var consectetur = new Consectetur()
var elit = new Elit()

println( Lorem ipsum dolor sit amet ,
consectetur adipisicing elit. Ut enim )
}
}
The intrepid developer smiles at the output:

Darn you, Weiqi!
((),It is late on a Friday)
Quietly, he turns to the window and watches the clouds pass across a moon-filled sky. An evening well-spent.

ps. This is a good exercise for a newcomer to Scala. Though the next logical step is much more interesting: write a Scala program that accepts the Latin text as input and generates a Scala program that can use the phrase as a pseudo DSL.

1 comment:

Tom said...

Worth noting that you can "Greek" in Java, too, if you want. It just requires more punctuation. Just to refute a bit of Weiqi Gao's original argument. The part he gets right is that people too often want to be clever in Scala. Hopefully that part of the attitude is overcome by the folks that like clarity. Because Scala can be very readable too (and more so than Java if it's your goal).