Sunday, August 26, 2007

lasreveR gnirtS

It's not hard to determine the output from the little Groovy Puzzler. (Spoiler ahead).

It reverses a string. Since the post, I've wondered about this little refinement:

Write a terse Groovy program that reverses a string. How terse can you go?

For Groovy experts, this is pretty easy. As I've poked at this (as an intermediate), here's what I've found out along the way (starting with the Puzzler above).

Evaluate() is Powerful

No surprise here. The ability to execute data can be tremendously useful. Check this out:

evaluate('print args[0][i---1];'*i)

This program checks in at 55 characters. The key is the '*' operator which generates a string. For example, 'abc' * 3 = 'abcabcabc'. This generates a sequence of print statements, which is executed by evaluate. Note that evaluate has a sense of context (e.g. the variable 'i').

Another way to see what is happening:
print args[0][ (i--) - 1 ]; // print args[0][N-1]
print args[0][ (i--) - 1 ]; // print args[0][N-2]
print args[0][ (i--) - 1 ]; // print args[0][N-3]
... etc

'Tis hardly efficient but my favourite of these programs.

Home on the Range

Python has fantastic flexibility in indexing arrays. As it turns out, Groovy does too, with ranges. Surely there is way to exploit this to tighten the terse factor:

println args[0][args[0].length()-1..0]

That's a trim 39 characters. We just let the reverse range iterate over the string.

KISS rocks

Many of you knew this all along: keep it simple. If you check out the list of methods that Groovy adds to the JDK (see it here), then things get much easier. And, I think, optimally terse!

println args[0].reverse()

That's 26 characters and just one calorie.

The Upshot

The upshot isn't to strive for terse programs. The point is that the "what if?" questions can be a cool way to learn about a language's capabilities.

No comments: