BrowserUk has asked for the wisdom of the Perl Monks concerning the following question:
Inspired by having recently worked my way through Aristotle's nice article on the Y Combinator in Perl, I wondered if Howto avoid large hard-coded else-if function calls could be done using a similar technique. I eventually got it to go, but only by moving to 5.8.8 (rather than 5.8.6) and applying some hacks to work around (further) limitations of the List::Util::reduce() operator.
In the following code, the list of functions to be applied are built up (curried?) together to produce a single code ref that can be applied to the inputs and produce the outputs in a single pass (kinda):
#! perl -slw require 5.8.8; use strict; use List::Util qw[ reduce ]; $a = $b; my %dispatch = ( A => sub{ map{ $_ +1 } @_ }, B => sub{ map{ $_ *2 } @_ }, C => sub{ map{ $_**2 } @_ }, D => sub{ map{ $_ +3 } @_ }, E => sub{ map{ $_ *5 } @_ }, ); my $func_com = $ARGV[ 0 ] || 'ABC'; my @some_val = 1 .. 10; my $combo = reduce{ { ## 1 my( $x, $y ) = ( $a, $b ); ## 3 $a = sub{ $y->( $x->( @_ ) ) } } ## 2 } map{ $dispatch{ $_ }||sub{ @_ } } split '', $func_com; printf "[ %s ]", join ',', $combo->( @some_val ); __END__ c:\test>\AS817\perl\bin\perl5.8.8.exe junk6.pl ABCDE [ 95,195,335,515,735,995,1295,1635,2015,2435 ]
The hacks (this doesn't work before 5.8.8 because of closure bugs with reduce() that got recently fixed):
Shouldn't the outer bare block be sufficient to form the closures?
It's perfectly possible to close over package globals in other instances, so is this a bug?
Or is it the alias nature of $a & $b that prevents the closure working correctly?
Both hacks are still required of 5.8.9 5.9.x (circa a month or so ago), so are either or both worth raising a perlbug over?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Bugs? Or only in my expectations?
by Corion (Patriarch) on Jun 24, 2007 at 10:10 UTC | |
by BrowserUk (Patriarch) on Jun 24, 2007 at 16:56 UTC | |
by bart (Canon) on Jun 24, 2007 at 23:46 UTC | |
by BrowserUk (Patriarch) on Jun 25, 2007 at 05:04 UTC | |
by polettix (Vicar) on Jun 25, 2007 at 14:19 UTC | |
|
Re: Bugs? Or only in my expectations?
by ikegami (Patriarch) on Jun 24, 2007 at 17:36 UTC | |
|
Re: Bugs? Or only in my expectations?
by ysth (Canon) on Jun 24, 2007 at 18:23 UTC |