Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
generalize List.reduce
Now does both N-ary reducers with left or right associativity, and
all the standard reducers for binary functions of any associativity.
  • Loading branch information
TimToady committed Mar 31, 2015
1 parent 76ba0a2 commit f65ba97
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
23 changes: 17 additions & 6 deletions src/core/List.pm
Expand Up @@ -608,13 +608,24 @@ my class List does Positional { # declared in BOOTSTRAP
}

method reduce(List: &with) {
fail('can only reduce with arity 2')
unless &with.arity <= 2 <= &with.count;
return unless self.DEFINITE;
my \vals = self.values;
my Mu $val = vals.shift;
$val = with($val, $_) for vals;
$val;
return self.values if self.elems < 2;
if &with.count > 2 and &with.count < Inf {
my $moar = &with.count - 1;
my \vals = self.values;
if try &with.prec<assoc> eq 'right' {
my Mu $val = vals.pop;
$val = with(|vals.splice(*-$moar,$moar), $val) while vals >= $moar;
return $val;
}
else {
my Mu $val = vals.shift;
$val = with($val, |vals.splice(0,$moar)) while vals >= $moar;
return $val;
}
}
my $reducer = find-reducer-for-op(&with);
$reducer(&with)(self) if $reducer;
}

method sink() {
Expand Down
3 changes: 2 additions & 1 deletion src/core/LoL.pm
Expand Up @@ -41,7 +41,8 @@ class LoL { # declared in BOOTSTRAP
sub lol (**@l) { @l }

sub find-reducer-for-op($op) {
my %prec := $op.prec;
try my %prec := $op.prec;
return &METAOP_REDUCE_LEFT unless %prec;
my $reducer = %prec<prec> eq 'f='
?? 'listinfix'
!! %prec<assoc> || 'left';
Expand Down

0 comments on commit f65ba97

Please sign in to comment.