Comparing Lines of Code: Scala and Clojure (FUD version)
A completely tongue in cheek comparison between Scala and Clojure, implementing the famous closure test.
Scala Version1
type Supercalifragilisticexpialidocious = java.lang.Integer
implicit def Supercalifragilisticexpialidocious2Int(tehThingToConvert:Supercalifragilisticexpialidocious) = {
tehThingToConvert.asInstanceOf[Int]
}
trait ClosureTestMixin {
def makeAdder(tehAdditionValue:Supercalifragilisticexpialidocious):Function1[Int,Int]
}
class AdderMaker extends ClosureTestMixin {
def apply(tehAdditionValue:Supercalifragilisticexpialidocious):Function1[Int,Int] = {
new Function1[Int,Int] {
def apply(tehOtherAdditionValue:Int):Int = {
return tehAdditionValue.$plus(tehOtherAdditionValue.asInstanceOf[Supercalifragilisticexpialidocious])
}
}
}
def makeAdder(tehAdditionValue:Supercalifragilisticexpialidocious):Function1[Int,Int] = {
return this.apply(tehAdditionValue)
}
}
val tehAdderMakerInstance = new AdderMaker()
val tehAdderPlus10 = tehAdderMakerInstance.makeAdder(10)
tehAdderPlus10.apply(9)
//=> 19
Clojure Version
(defn mk-adder [x] #(+ % x))
(def add10 (mk-adder 10))
(add10 9)
;=> 19
To perform this simple exercise the Scala version requires2 29 lines and ~960 characters! The Clojure version on the other hand requires only 3 lines and 64 characters.
Need I say more?3
-m
-
Any suggestions for making this longer? ↩
-
Nope, not at all. ↩
-
Just in case there was any ambiguity — the Scala version was intentionally obfuscated for chuckles. For a much more eloquent rebutal of flawed LOC comparisions read Stephan Schmidt’s latest post on the subject. ↩
7 Comments, Comment or Ping
Gabriel C
You should replace the “+” in the Scala code with “$plus”, a beginners mistake, but hey, we’re all learning :) Also, consider making it a monad…
Jan 4th, 2010
fogus
@Gabriel Done! I will play around later with making the Scala version more monadic. Thanks for the tips!
Jan 4th, 2010
Josh Cough
:) can you do it in reverse too?
Jan 4th, 2010
Daniel E. Renfer
I can’t believe you wasted so many lines in your Clojure version.
(((fn mk-adder [x] #(+ % x)) 10) 9)
only 35 characters and does roughly the same thing. :)
Jan 4th, 2010
fogus
@Josh Cough
That will be the next post. :-)
Jan 6th, 2010
Leo
I am also new to Scala. Not quite sure about the closure test Why we could not use below in Scala? I think it’s quite similar to the 29 lines code
def addPlus10: Function1[Int, Int] = 10 + _ addPlus10(9)
Mar 25th, 2010
Edward
Just started Scala with Martin Odersky’s Coursera course and Week 2 covered higher order functions.
I think this should do it, seems pretty easy actually.
def makeAdder(incr: Int): Int=>Int = x => x + incr def plus10 = makeAdder(10) plus10(9)
Yes I realise this post is an old joke, but I wanted to apply what I had learned.
Oct 1st, 2012
Reply to “Comparing Lines of Code: Scala and Clojure (FUD version)”