Summing elements
Here, the original Ruby example printed the result, but I've trimmed that out for consistency with the rest of the examples.
Ruby:
my_array.inject(0){|sum,item| sum + item}
Python: sum(my_list)
Perl 6: [+] @my_array
Double every item
Ruby:
my_array.map{|item| item*2 }
Python: [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)
Ruby:
my_array.find_all{|item| item % 3 == 0 }
Python: [x for x in my_list if x % 3 == 0]
Perl 6: grep {$^item %% 3}, @my_array
# or...
grep * %% 3, @my_array
Combine techniques
Ruby:
my_array.find_all{|item| item % 3 == 0 }.inject(0){|sum,item| sum + item }
Python: sum(x for x in my_list if x % 3 == 0)
Perl 6: [+] grep * %% 3, @my_array
Sorting
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.
Ruby:
my_array.sort
my_array.sort_by{|item| item*-1}
Python: sorted(my_list)
sorted(my_list, reverse=True)
Perl 6: @my_array.sort;
@my_array.sort: -*;
And there you have it. Enjoy the many choices you have in programming languages!
No comments:
Post a Comment