Thursday, June 3, 2010

5 things you can do with Lists in Perl 6, Python and Ruby

I think practical examples of doing the same sorts of tasks in different programming languages can be wonderful tools. Recently, an IT student in Poland named Konrad posted a followup on his blog to the 2007 Ruby blog, "5 things you can do with a Ruby array in one line (PLUS A FREE BONUS!!)" by drewolson. He updated this for Python. Of course, having worked with Perl 6 quite a lot recently (see my Google Buzz posts titled "Your daily dose of Perl 6"), I was compelled to do the same for that language. See below for the results. Notice that Konrad chose temporary variable names that were much shorter than drewolson's, so the visual comparison between Ruby and Pyhthon in terms of code size is somewhat unfair, but I'll go with the original names where I need temporaries, just to be fair to Ruby.

Summing elements

Here, the original Ruby example printed the result, but I've trimmed that out for consistency with the rest of the examples.

  my_array.inject(0){|sum,item| sum + item}
Perl 6:
  [+] @my_array

Double every item

Ruby:{|item| item*2 }
  [2 * x for x in my_list]
Perl 6:
  @my_array <<*>> 2

Finding all items that meet your criteria (such as being divisible by 3)

  my_array.find_all{|item| item % 3 == 0 }
  [x for x in my_list if x % 3 == 0]
Perl 6:
  grep {$^item %% 3}, @my_array
  # or...
  grep * %% 3, @my_array

Combine techniques

  my_array.find_all{|item| item % 3 == 0 }.inject(0){|sum,item| sum + item }
  sum(x for x in my_list if x % 3 == 0)
Perl 6:
  [+] grep * %% 3, @my_array


For more information on how Perl 6 sorting works and what the *-autoclosure syntax that I've used above does, see carl's excellent Perl 6 Advent Calendar post.

  my_array.sort_by{|item| item*-1}
  sorted(my_list, reverse=True)
Perl 6:
  @my_array.sort: -*;

And there you have it. Enjoy the many choices you have in programming languages!

No comments:

Post a Comment