Some interesting comments on yesterday's Haskell post. I thought I'd write this in Perl to compare. Of course, we don't have an "inits" function in the standard library, but that's easily written:
#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper;
my %hash = (
"key1" => 1,
"key2" => 2,
"other" => 3,
);
sub inits {
my $string = shift or return;
return ($string, inits( substr($string, 0, -1)) );
}
sub getPrefixMap {
my %hash = @_;
return map {
my $k = $_; my $v = $hash{$_};
map { ($_ => $v) } inits $k;
} keys %hash;
}
my %map = getPrefixMap( %hash );
print Dumper( \%map );
This is a bit noisier, but perhaps more straight-forward than the final haskell version…
Update: broquaint pointed out that the code listing above was missing the zero in the substr, breaking it. Thanks!