Skip to content

Instantly share code, notes, and snippets.

@Util
Created June 13, 2022 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Util/efc065591a31156afca70ccc474c9959 to your computer and use it in GitHub Desktop.
Save Util/efc065591a31156afca70ccc474c9959 to your computer and use it in GitHub Desktop.
# Trying for a simpler version of https://gist.github.com/gfldex/e28992d7d85451ed669e7942f0b27e30 ,
# because it gets down to the Iterator level, and also evaluates its condition twice for every value.
# All of these versions use the L1 record-matching logic I learned way back in
# the RPG language (where it was built into the language itself as L1,L2...L9 and MR indicators).
# Evaluates its condition N+1 times
sub batch2 (@list, &cluster) {
return lazy gather {
my @r;
my $last_val = cluster(@list[0]);
for @list -> $e {
my $c = cluster($e);
if $last_val !eqv $c {
$last_val = $c;
take [@r];
@r = Empty;
}
push @r, $e;
}
take @r if @r;
}
}
.say for [0..1000].&batch2(*.chars);
# Evaluates its condition N times, at a cost of checking $first on each loop.
# Also uses $r instead of @r, for variety (or maybe clarity? I am unconvinced).
sub batch3 ( @list, &cluster ) {
return lazy gather {
my $r = [];
my $last_val;
my $first = True;
for @list -> $e {
my $c = cluster($e);
if $first {
$first = False;
$last_val = $c;
}
if $last_val !eqv $c {
$last_val = $c;
take $r;
$r = [];
}
$r.push: $e;
}
take $r if $r.elems;
}
}
.say for [0..1000].&batch3(*.chars);
# Evaluates its condition N times, without any extra cost,
# by using the fact that `state` resets on subsequent calls to batch4().
# XXX `state` may cause this version of be thread-unsafe?
sub batch4 ( @list, &cluster ) {
return lazy gather {
my $r = [];
for @list -> $e {
my $c = cluster($e);
state $last_val = $c;
if $last_val !eqv $c {
$last_val = $c;
take $r;
$r = [];
}
$r.push: $e;
}
take $r if $r.elems;
}
}
.say for [0..1000].&batch4(*.chars);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment