Tuesday, January 26, 2010

String interpolation in Scala with Regex

Some new stuff I was waiting for has arrived on Scala. We can now have a limited form of string interpolation very easily:

def interpolate(text: String, vars: Map[String, String]) =
"""\$\{([^}]+)\}""".r.replaceAllIn(text, (_: scala.util.matching.Regex.Match) match {
case Regex.Groups(v) => vars.getOrElse(v, "")

Which can then be used like this:

scala> "The ${name} of the ${game}"
res0: java.lang.String = The ${name} of the ${game}

scala> Map("name" -> "X", "game" -> "Y")
res1: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(name -> X, game -> Y)

scala> interpolate(res0, res1)
res2: String = The X of the Y

Friday, January 8, 2010

Why do I love APL?

I love the strangest languages for various reasons. Some of them have immense power, but can easily produce unmaintainable messes. Some have the elegant simplicity of zen, but never attracted the people who build kitchen sinks. Some are perfect matches for certain applications, and quickly degenerate for other usages.

In Scala I have found for the first time a positive combination of these attributes. Immense power, kitchen sinks, check. Simplicity? Perhaps not, but more so than the more popular alternatives. Some code has definitely a zen-like quality to it. And, yet, it is of general use, and has good enough resilience against unmaintainable messes. Not perfect, but better than anything else I know of, for now.

That doesn't mean I do not appreciate other languages. There is much to learn and admire in many, many languages, and I would not mind using quite a few of them if chance favors it.

So I'll leave you with the answer that came to my mind as I explained to a bewildered person why I loved APL -- a language I could spend a whole afternoon producing half a line of code:

There's joy to be found in writing code which is solely about what you want, and not about how to get there. Of expressing the fulness of your intent as a single expression. It's like the ultimate perfect katana cut.

Of course, in a real fight I'd rather have a gun.