You're right. I misread your original post. What threw me off was the mention of streams. In the solution you present (which is indeed entirely different from merging lists), using lazy lists seems forced to me, since their properties don't get you anything that you couldn't get very easily and directly with grep and the '..' operator:
use strict;
# use Stream;
use Math::Pari qw(gcd);
# We can test all the factors at once using the greatest common diviso
+r algorithm.
my @factors = @ARGV;
my $test_number = 1;
$test_number *= $_ for @factors;
die "Must provide a list of non-zero factors\n" unless $test_number >
+1;
sub has_common_factor { gcd($_[0], $test_number) != 1 }
# my $integers = Stream::tabulate( sub { $_[0] }, 1);
# my $challenge = $integers->filter(\&has_common_factor);
# $challenge->show(50);
print "@{[grep has_common_factor($_), 1..50]}\n";
Thanks for pointing out the Streams module. It does some very nice things which I think I should incorporate in my stab at implementing lazy lists. It doesn't use memoization, however, which I think is absolutely essential to a workable implementation of lazy lists, at least in Perl5. What's most curious about this is that Dominus is the author of the Memoize module! Then again, the module is not available from CPAN. I suspect that both these facts have to do with realizing that this sort of object requires a little more syntactic support from Perl to be worth doing.
Update: Oh, yes. There's memoization in Stream.pm, all right; it's just done very discreetly (and elegantly, IMO):
sub tail {
my $t = $_[0]{t};
if (ref $t eq CODE) { # It is a promise
$_[0]{t} = &$t; # <--- there!
}
$_[0]{t};
}
BTW the execution time of my merged-lists solution is not growing anywhere nearly as fast as the formula you gave (not that it matters a whole lot, but I give the stats below if anyone's interested). Still, the gcd-based solution is noticeably faster; whether this is the result of the fact that most of its heavy lifting (the gcd calculation) is done by a C routine, or something more fundamental is not yet clear to me.
|