http://www.perlmonks.org?node_id=441347


in reply to Challenge: Another Infinite Lazy List


My solution in the root thread required was only minimally better than my original solution (to the wrong problem). This minimally tested version is vast improvement over both previous solutions.
#!/usr/bin/perl use strict; use warnings; my $end = shift || 22; my $next = lazy_merge( [ @ARGV ? @ARGV : (2, 3, 5) ] ); print $next->(), "\n" for 1 .. $end; sub lazy_merge { my ($list, $last) = (shift(), 0); my $by_n = sub { my ($n, $k) = (shift(), 0); return sub { $_[0] ? +$k += $n : $k } }; $_ = $by_n->( $_ ) for @$list; return sub { my $low; for ( @$list ) { my $val = $_->(); $val = $_->( 'next' ) if $val <= $last; $low = $val if ! defined $low || $val < $low; } return $last = $low; }; }

Cheers - L~R