Closures

October 2nd, 2004

Following my last post it was pointed out to me that Martin Fowler did a brief intro to closures last month, including a handful of Ruby examples. This was followed by translations into C#, and Python (two forms, simple and idiomatic). All of which brought home just how lovely Python’s list comprehension is. (how little I like statically typed languages) Maybe I should add list comp to the list for PHP 6?

Strangely Fowler didn’t cover what I consider to be the most useful/powerful feature of closures, anonymous functions (aka “code refs” in Perl speak).

Rather then hard coding you’re looking for managers, as in Fowler’s example, ayou might instead create a factory method for searching for arbitrary employee types.

In Perl this might look like:

sub makeEmployeeFilter {
  my $type = shift;
  return sub { my $e = shift; return $e->isOfType($type); }
}

$isManager = makeEmployeeFilter('Manager'); grep { $isManager->($_) } @emps;

Tagged: Uncategorized

Leave a Reply