20 September 2009

Scala and idioms

From the article : Is Scala really more complicated than Java? The same program can be written in Scala with different idioms:

Easy way:

val name = "Dick Wall"
println("""
Happy Birthday to you
Happy Birthday to you
Happy Birthday dear """ + name + """
Happy Birthday do you
""")


Procedural:
for (n <- 1 to 4) {   
print("Happy Birthday")
if (n == 3)
print(" dear XXX")
else
print(" to you")
println
}


Mixed:

(1 to 4).map {
i => "Happy Birthday %s".format(if (i == 3) "Dear XXX" else "To You")
}.foreach println


Functional:

(List.make(4, "Happy birthday ")
zip (List.tabulate(4, {
case 2 => "dear friend"
case _ => "to you"}))
) map (Function.tupled(_+_)) mkString ("\n")


More freedom ? hope Scala will avoid to be like Perl ! Not everybody will be able to maintain a Scala program. But that is also true with Java or anything. The complexity can be everywhere anyway, it is just more or less visible.

Read also: It's not the languages, but their idioms that matter.
Post a Comment

October summary - 2017-10

10 October Science Looks like the p-value has been under fire for years. https://www.nature.com/news/one-size-fits-all-threshold-for-p-value...