Created
September 2, 2010 17:17
-
-
Save ajs/562575 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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