Here are my solutions to Problem 9. The first is concise and looks fairly efficient.
The second is less straightforward; I wanted to solve it with one big map, in
the hopes of allowing it to work lazily. I don't know how to tell if I
succeeded, though.
Code tested in Pugs:
sub p09_group_Util_1 (*@list) {
my @ret;
for @list -> $val {
push @ret, [] if !@ret or $val !~~ @ret[-1][-1];
push @ret[-1], $val;
}
return @ret;
}
sub p09_group_Util_2 (*@list) {
my @tmp;
return map -> $index, $val {
my @ret;
if !@tmp or $val !~~ @tmp[-1] {
@ret = [ @tmp ] if @tmp;
undefine @tmp;
}
push @tmp, $val;
push @ret, [ @tmp ] if @tmp and $index == @list.end;
@ret; # May contain 0, 1, or 2 arrayrefs.
}, @list.kv;
}
my @data = <a a a a b c c a a d e e e e>;
say '9.1 ', p09_group_Util_1(@data).perl;
say '9.2 ', p09_group_Util_2(@data).perl;
# When dumped via .perl, Util_1 is wrapped in [], and Util_2 in ().
# When dumped via .yaml, Util_1 and Util_2 are identical. Bug?
Output:
9.1 [["a", "a", "a", "a"], ["b",], ["c", "c"], ["a", "a"], ["d",], ["e
+", "e", "e", "e"]]
9.2 (["a", "a", "a", "a"], ["b",], ["c", "c"], ["a", "a"], ["d",], ["e
+", "e", "e", "e"])