Funky Function Filters

Created 2006-03-03 / Edited 2006-03-03

Guido van Rossum Re-Posted a plea for advertisement of Python. Some of the Python folks are feeling the Ruby squeeze and feel like their leader might be able to make some noise.

Anyway, in the course of the conversation Guido asked what the Ruby equivalent for this would be:

for f in filter(lambda f: f(-1)>=f(1),
                [lambda x:x, lambda x:x**2, lambda x:x**3]):
    for x in range(-10, 11):
        print x, f(x)

Which is, of course, a completely useless piece of code demonstrating some lambda functionality. Someone posted the response:

for f in [lambda { |x| x }, lambda { |x| x**2 }, lambda { |x| x**3 }
         ].select { |f| f.call(-1) >= f.call(1) }
    for x in -10..10
        print x, f.call(x)
    end
end

Which is quite similar. I thought I'd give it my hand for Perl5, which looks like this:

for $f (grep {$_->(-1)>=$_->(1)} (
        (sub{shift},sub{(shift)**2},sub{(shift)**3}) {
  for $x (-10,10) {
    print $x," ",$f->($x),"\n";
  }
}

Pretty ugly, if I do say so myself. The uglyness comes directly from the lack of a simple named parameter mechanism. The Python and Ruby versions look, like I said, very similar. All three are identical in algorithm... but for once it looks like Perl doesn't do so well on terseness.

Now I have to figure out what this looks like in Perl6...