Perl also lets you use parameters to roll your own block syntax. Here is a slightly different definition that would allow you to do arbitrary operations on the first element of each run in a list:
sub compress(&@) { my $cr=shift; my$x; my @aResult; local $_=undef; foreach (map { defined($x) ? defined($_) && ($x eq $_) ? () : ($x = $_) : defined($_) ? ($x = $_) : () } @_) { push @aResult, $cr->(); } return @aResult; } my @aData=(qw(a a a a b c c a a d e e e e), undef, undef, qw(f g g)); my @aCompressed = compress {'*' . (defined($_)?$_:'<undef>').'*'} @aData; print "compress: @aCompressed\n"; # output: compress: *a* *b* *c* *a* *d* *e* *<undef>* *f* *g*
Or if you want to be able to work with the current run value ($b) and the previous run value $a, you could do something like this:
sub compressPair(&@) { my $cr=shift; my @aResult; my $x; local $a=undef; local $b=undef; foreach (map { defined($x) ? ($x eq$_?():($x=$_)) : defined($_)?($x=$_):() } @_) { $a=$b; $b=$_; push @aResult, $cr->(); } return @aResult; } my @aData=(qw(a a a a b c c a a d e e e e), undef, undef, qw(f g g)); my @aCompressed = compressPairs { '(' . (defined($a)?$a:'<undef>') . ',' . (defined($b)?$b:'<undef>') . ')' } @aData; print "compressPairs: @aCompressed\n"; #output compressPairs: (<undef>,a) (a,b) (b,c) (c,a) (a,d) (d,e) (e,<undef>) ( +<undef>,f) (f,g)
There is almost no limit to what you could create. For example, if you wanted to be able to group items, you could additionally track the number of items in each run and set $_ to number of items in the current run:
sub compressPairsWithCount(&@) { my $cr=shift; my @aResult; my $x; my @aRuns=(0); my $i=defined($_[0])?-1:0; my $j=0; local $a=undef; local $b=undef; foreach (map { if ((defined($x) && defined($_) && ($x eq $_)) || (!defined($x) && !defined($_))) { $aRuns[$i]++; () } else { $aRuns[++$i]=1; ($x = $_); } } @_) { $a=$b; $b=$_; $_=$aRuns[$j++]; push @aResult, $cr->(); } return @aResult; } @aCompressed = compressPairsWithCount { '(' . (defined($a)?$a:'<undef>') . ',' . (defined($b)?$b:'<undef>') . "=$_)" } @aData; print "compressPairsWithCount: @aCompressed\n"; #outputs compressPairsWithCount: (<undef>,a=4) (a,b=1) (b,c=2) (c,a=2) (a,d=1) +(d,e=4) (e,<undef>=2) (<undef>,f=1) (f,g=2)
Would that do what you want?
Update: added yet another block iterator, this time one that could be used for generating groups as in the Haskell function above.
Update: put in readmore tags
Update: fixed 3rd example so it prints count of current (not previous) run.
In reply to Re^3: reduce like iterators
by ELISHEVA
in thread reduce like iterators
by LanX
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |