Sunday, August 30, 2009

Discussion about anonymous function in Perl and Ruby

Just for fun, tonight I write a methods invoking two anonymous functions to iterate a Range with specified condition in Ruby. It looks like
class Range
def each_satisfy()
And I want to invoke it as

(1..10).each_satisfy(condition_lambda, callback_lambda)

(1..10).each_satsify { |n| ...condition statment... } do |n|
...callback statement...
When I try to define its prototype as
def each_satisfy(&condition, &callback)
Ruby Interpreter broke with syntax error. So that, finally I write it as

def each_satisfy(condition, &callback)
self.each do |n|
yield n if n
and it should be used as

(1..10).each_satsify lambda { |n| ...condition statment... } do |n|
...callback statement...

It reminded me that Perl also has the same problem. Even when we declare

sub each_satisfy(&&) {


Still only first sub keyword could be omitted. That means we should invoke it as

each_satisfy { ... condition ... } sub {
my ($iter) = @_;
... callback ...

The only difference is Perl omitted the first (sub) and Ruby omitted the last (lambda).

I do want to figure out WHY they could not be designed to accept arbitrary quantity of anonymous functions.


1 comment:

chorny said...

Maybe you can do it with Perl's Devel::Declare/B::Hooks::Parser, but your code will be much more complex.