aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFrancis Whittle <FJ.Whittle@gmail.com>2019-04-12 22:48:58 +1000
committerFrancis Whittle <FJ.Whittle@gmail.com>2019-04-13 13:31:46 +1000
commit747e157fdd867b1af3d98562cb5b1954c6e5a757 (patch)
tree4d7e4871fc571540194e6248719062391c377685
parent621d4f7037e73f35025a119bd74ef90645f754bf (diff)
downloadperlweeklychallenge-club-747e157fdd867b1af3d98562cb5b1954c6e5a757.tar.gz
perlweeklychallenge-club-747e157fdd867b1af3d98562cb5b1954c6e5a757.tar.bz2
perlweeklychallenge-club-747e157fdd867b1af3d98562cb5b1954c6e5a757.zip
fjwhittle / Update ch-1 to use iterators, more elegant loop
-rw-r--r--challenge-003/fjwhittle/perl6/ch-1.p630
1 files changed, 10 insertions, 20 deletions
diff --git a/challenge-003/fjwhittle/perl6/ch-1.p6 b/challenge-003/fjwhittle/perl6/ch-1.p6
index 25785ed2e2..0232dfceba 100644
--- a/challenge-003/fjwhittle/perl6/ch-1.p6
+++ b/challenge-003/fjwhittle/perl6/ch-1.p6
@@ -11,34 +11,24 @@ unit sub MAIN(
);
# Use a lazy list to generate 5-smooth numbers
-my @smooth5 = lazy gather {
- take 1; # 1 is the first
-
- # Initialize some iteration counters.
- my ($i2, $i3, $i5) = 0 xx 3;
-
- # I wanted to use actualy Iterators here, but couldn't figure out how to not
- # pull elements that didn't exist yet.
-
- # Generate the next number for each divisor
- my $n2 = @smooth5[$i2++] * 2;
- my $n3 = @smooth5[$i3++] * 3;
- my $n5 = @smooth5[$i5++] * 5;
+my $smooth5 = gather {
+ # Initialize some iterators.
+ my ($i2, $i3, $i5) := ($smooth5.iterator for ^3);
+ my ($n2, $n3, $n5) := 1 xx 3;
# Just keep generating. Does the list become sparse? I don't know!
loop {
# Minimum of the latest iterations
- my $n = ($n2, $n3, $n5).min;
- take $n;
+ take my $n := ($n2, $n3, $n5).min;
- # Advance the generators that matched.
- $n2 == $n and $n2 = @smooth5[$i2++] * 2;
- $n3 == $n and $n3 = @smooth5[$i3++] * 3;
- $n5 == $n and $n5 = @smooth5[$i5++] * 5;
+ # Advance the iterators that matched.
+ $n2 == $n and $n2 := $i2.pull-one * 2;
+ $n3 == $n and $n3 := $i3.pull-one * 3;
+ $n5 == $n and $n5 := $i5.pull-one * 5;
}
}
-@smooth5.[^$count].say;
+$smooth5.[^$count].say;
for @print -> $n {
($n.fmt('%7d') ~ ': ' ~ @smooth5[$n-1]).say;