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:
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
evaluatehas a sense of context (e.g. the variable 'i').
Another way to see what is happening:
print args[ (i--) - 1 ]; // print args[N-1]
print args[ (i--) - 1 ]; // print args[N-2]
print args[ (i--) - 1 ]; // print args[N-3]
'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:
That's a trim 39 characters. We just let the reverse range iterate over the string.
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!
That's 26 characters and just one calorie.
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.