[tpm] fun with closures

Viktor Pavlenko vvp at cogeco.ca
Fri Sep 14 12:50:49 PDT 2007


Hi all,

here is a functional associated list I translated from an example in
an Ocaml book, I thought it was pretty cool, so decided to share:

$ cat assoc_closures.pl
----------------------------------------------------------------
#!/usr/bin/perl -w

use strict;

sub nil_assoc {
    sub { die "not found\n" }
}

sub add_assoc {
    my ($k,$v,$l) = @_;
    sub { my $x = shift; return ($x eq $k) ? $v : &$l($x) }
}

my $arg = shift;

my $alist = nil_assoc;
$alist = add_assoc($_, ord($_), $alist) for 'a'..'z';

print $arg, ' => ', &$alist($arg), "\n";
----------------------------------------------------------------
$ ./assoc_closures.pl a
a => 97
$ ./assoc_closures.pl b
b => 98
$ ./assoc_closures.pl x
x => 120
$ ./assoc_closures.pl Q
not found
$ 

Have a good weekend!

Cheers,

-- 
Viktor



More information about the toronto-pm mailing list