Thursday, April 17, 2008

Converting Groovy to Ruby

In this post, Glen Stampoultzis posts a very interesting and clever sequence of steps by which he converts a piece of Java code into idiomatic Groovy code. I thought it was a nice article, so I'll do a very short spin on it: taking Glen's final Groovy code and converting it into idiomatic Ruby.

(I'll probably get my pants flamed off by you-know-who, but hey, it's a slow Thursday afternoon.)

Glen's code, an algorithm for finding all n-length subsequences in a given array, ends up here:

def subn(n, list) {
if (n == 0) return [[]];
if (list.isEmpty()) return [];

def remainder = list.subList(1, list.size());
return subn(n-1, remainder).collect() { [list.get(0)] + it } + subn(n, remainder);
(I had to make some edits because his code didn't appear to format right; I don't claim this code is 100% correct in this state.) Admittedly it's a very nice reduction from the original Java code. As Glen correctly surmises, it's largely due to those super-nice closures we get from Groovy. My first step is to make a few minor changes to make it run correctly in Ruby:
def subn(n, list)
return [[]] if (n == 0);
return [] if (list.empty?());

remainder = list.slice(1, list.size());
return subn(n-1, remainder).collect() {|it| [] + it } + subn(n, remainder);
The most notable changes here are flopping the statement-modifying conditionals on the first two returns and adding an "it" parameter to the collect block. Oh, there's also the "empty?" method. But largely it looks like pretty much the same code. The next obvious step is to remove things that aren't needed in Ruby.
def subn(n, list)
return [[]] if n == 0
return [] if list.empty?

remainder = list.slice(1, list.size)
return subn(n-1, remainder).collect {|it| [] + it } + subn(n, remainder)
Mostly just removing some parens that are unnecessary (and distracting, for me) as well as line-terminating semicolons. Note that Groovy also can omit line-terminating semicolons. I think it's a matter of taste.
def subn(n, list)
return [[]] if n == 0
return [] if list.empty?

remainder = list[1..-1]
subn(n-1, remainder).collect {|it| [list[0]] + it } + subn(n, remainder)
Now we've eliminated the last "return" statement and made the list accesses use the array-referencing "[]" the first case with a more idiomatic range of values rather than two parameters. Again, a matter of taste I suppose; two arguments works just fine. So that brings us mostly to the end of converting from the original Groovy code into Ruby. The new version is as readable as the original, but shorter by several characters. And of course this is my biased opinion, but it reads nicer too. I'm sure that will bring about all sorts of flaming in itself.

At any rate, my point in this is certainly not to start a flame war about which version is better. My point is that the Groovy and Ruby versions are still largely the same. If you can learn to produce the Groovy end result, you can just as easily learn to produce the Ruby end result. So if you've stuck with Java because you're worried you can't learn Ruby, or you don't think Ruby is enough like Java...don't be scared! A whole Rubylicious world awaits you :)

(Oh, and for you Rubyists out there...feel free to post your own improvements in the comments. I didn't want to change the original flow of the code, but I know it can be golfed down a lot more.)


Anonymous said...

Seems to me that the Groovy version can be reduced further:

def subn(n, list) {
 if (!n) return [[]]
 if (!list) return []

 def remainder = list[1..-1]
 return subn(n-1, remainder).collect() { [list[0] + it } + subn(n, remainder);

Anonymous said...

Hmm, that makes them exactly the same number of characters, Groovy's two extra "()" pairs on the if statements traded for Ruby's definition of "|it|".

Sam said...

The biggest difference is that from beginning to end as he is changing it from Java to Groovy the code continues to execute correctly so it much easier to do those incremental changes.

chewy said...

Just a quick followup on my site:

seano said...

Not golfing, just a different style - getting rid of returns altogether and using splat instead of indexing:

def subn(n, list)
if n == 0
elsif list.empty?
head, *tail = list
subn(n-1, tail).map {|it| [head, *it] } + subn(n, tail)


(Shame about the formatting)

Guillaume Laforge said...

In Mark's improved example, you can also even remove the last return keyword, to make it more idiomatic Groovy, and to save some more characters that the Ruby version.

But yes, both Groovy and Ruby are quite similar for that kind of algorithms: closures, colllect method taking a closure, list subscript operator, etc.

That's an interesting parallel to make here, and I wonder why you thought this article would be flamed? (hence why the useless sentences like "I'll be flamed by you-know-who"?)

Gavin Grover said...

def subn(n, list){
!n? [[]]: !list? []:
(list.size() == 1? []: list[1..-1]).with{
subn(n-1, it).collect{ [list[0]] + it } + subn(n, it)

assert subn(2, ['a','b','c']) ==
[["a", "b"], ["a", "c"], ["b", "c"]]

Anonymous said...

And a python version here:

def subn(n, lst):
if n > len(lst) or n < 0:
return []
elif n == 0:
return [[]]
return ( subn(n, lst[1:]) +
[ (lst[:1] + rest) for rest in subn(n-1, lst[1:]) ] )