Language Envy
I have been trying to port Joe Gregorio’s Robaccia framework into Groovy in my spare time. Robaccia is written in Python and since Groovy was
inspired by Python (and Ruby), I wanted to see how easily Python code can be translated into Groovy. Plus, I now realize there is no better way to learn
new languages than trying to translate relatively non-trivial pieces of code from one to the other.
In general, I have been able to translate Robaccia code into Groovy without line creep. A method in Python 5 lines long translates to a Groovy method 5 lines long. There is this one situation I ran into, where I have not been able to find a good translation. Here is the line(s) of code :
parts = ["a=10"]
params = dict([tuple([s.strip() for s in param.split("=")])\
for param in parts ])
Run this and you will find that given a list of strings, the string “a=10″ gets munged into a dictionary with the key “a” and a value of “10″. As an aside, try this in Java and let me know how many lines it took. Seamless transitions between data structures are a very useful feature in a programming language.
This is the best I could come with in Groovy. If anyone has a better way, please let me know. For some reason, I think the Python code looks cooler.
parts = ["a=10"]
map = new HashMap()
parts.each { List list = it.split("="); map.put(list[0].trim(), list.size > 1 ? list[1].trim() : null)}
