diff --git a/src/core/metaops.pm b/src/core/metaops.pm index 0ed70eb6321..a384fd7f5c3 100644 --- a/src/core/metaops.pm +++ b/src/core/metaops.pm @@ -96,6 +96,27 @@ our multi sub hyper(&op, $arg) { hyper(&op, $arg.list) } +our multi sub reducewith(&op, Iterable $an-iterable, :$chaining, :$right-assoc) { + my $ai = $an-iterable.iterator; + $ai = $ai.Seq.reverse.iterator if $right-assoc; + + my $result = $ai.get; + if $result ~~ EMPTY { + return &op(); + } + + loop { + my $next = $ai.get; + last if $next ~~ EMPTY; + if ($right-assoc) { + $result = &op($next, $result); + } + else { + $result = &op($result, $next); + } + } + $result; +} # degenerate case of operators, to be used by reduce() for the 0-ary case # this fails for operators defined in PIR, so some of them are commented out.