Skip to content

Instantly share code, notes, and snippets.

@ajs
Created September 2, 2010 17:17
Show Gist options
  • Save ajs/562575 to your computer and use it in GitHub Desktop.
Save ajs/562575 to your computer and use it in GitHub Desktop.
# Based on Python's itertools.tee, takes a list and a count and returns
# count number of iterators, each of which will "contain" all elements
# of the input list, but without evaluating/flattening the input list
# until needed.
#
sub tee(@list, :$count = 2) {
my @indices = 0...^$count;
my @inputs = @indices.map({[]});
my $maketee = -> $i {
gather loop {
if @inputs[$i].elems == 0 {
# Being careful not to flatten @list...
last unless ?@list;
my $next = @list.shift;
# Push the next item onto all inputs
for @indices -> $k {
@inputs[$k].push($next);
}
}
take @inputs[$i].shift;
}
}
gather for @indices -> $i {
take $maketee($i).item;
}
}
# Can't get this to behave lazily, even though simpler examples:
# ./perl6 -e 'sub a(@list) { @list.shift } ; say a(1...*)'
# seem to work fine.
my ($a,$b) = tee(1...*, :count(4));
say $a.WHAT;
for 0...* -> $i {
say $a[$i];
last if $i > 10;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment