Thursday, December 18, 2008

Scala Golf

Recently I pointed out how Scala has Golf built into it, in the form of the _. So of course it is fun to solve a Golf problem using Scala:

val m=scala.collection.mutable.Map.empty[Char,String]
args(1).split('|').map(_.split(',')).foreach((s)=>m+=s(0)(0)->s(1))
println(args(0).map((s)=>m.getOrElse(s,s)).mkString)

Another Golf friendly feature at work here is the apply method in Scala. It is defined on RichString as an alias for Java's String#charAt method. Given my Golf comment, it is unfortunate that the _ can't be used more in the above problem. Two of the closures needed to refer to the bound variable twice. If you use two _ then the compiler assumes the closure is taking two input parameters. Seems like you could infer the number of input parameters and allow more flexible use of _ ... which could make Scala even more expressive and even more confusing!

No comments: