Clojure

Control expressions are functions too

I am kind of simultaneously learning Clojure and Scala, the former through the London Clojure Dojo (come and join us) and the latter through work. It is an interesting experience but I am very glad that Clojure is part of the mix as it helps understand a lot of things that are seem strange in Scala.

In Clojure everything is essentially either a function or a sequence. It is therefore not surprising to see that an if statement works like a function.

(if false 1 2)

Evaluating the above in a Clojure REPL results in the answer 2: if is a function that evaluates its first argument returning the second parameter if the evaluation is true, the third if false.

The same is true of Scala, with the additional wrinkle that if the different clauses evaluate to different types you could be in type hell. Despite its superficial similarity to Java syntax it is in fact quite different and you can compose it just as you would any other function.

1 + (if(true) 2 else 3)

Evaluated in a Scala REPL gives the result 3.

Scala 2.8 seems much better about making everything return a value (and hence act like a function), val and for will both now return Unit, which is not useful but prevents the compiler moaning.

This kind of thing is much easier to appreciate and learn in a pure functional language than in Scala where you never really know whether something is going to operate in a functional or object-orientated way.

Standard
Scripting

Discovering Scala

Over the last two days I have been giving Scala a quick whirl and I have to say out of all the new languages (functional and otherwise) I have been looking at recently only Erlang is anywhere near as exciting. There is a small fifteen page tutorial and after finishing it I immediately thought: “I want to see more of that”.

I can’t put my finger on it at the moment but I imagine its the fact that it seems perhaps more familiar due to the Java background. The functional syntax is as confusing as any other functional language.

P.S. if you go through the short 15 page tutorial then there is a slight blip in the tutorial when case classes are introduced. All the code for the calculator example should be wrapped in an object block if you want it to work. I.e.

object Calculator {
... tutorial code
}

Standard