Yet another lazy evaluation in Perl
Version: 0.03Scalar::Lazy is yet another lazy evaluation in Perl.
License: Perl Artistic License
Operating System: Linux
Homepage: search.cpan.org
Developed by:
SYNOPSIS
use Scalar::Lazy;
my $scalar = lazy { 1 };
print $scalar; # you don't have to force
# Y-combinator made easy
my $zm = sub { my $f = shift;
sub { my $x = shift;
lazy { $f->($x->($x)) }
}->(sub { my $x = shift;
lazy { $f->($x->($x)) }
})};
my $fact = $zm->(sub { my $f = shift;
sub { my $n = shift;
$n < 2 ? 1 : $n * $f->($n - 1) } });
print $fact->(10); # 3628800
DISCUSSION
The classical way to implement lazy evaluation in an eager-evaluating languages (including perl, of course) is to wrap the value with a closure:
sub delay{
my $value = shift;
sub { $value }
}
my $l = delay(42);
Then evaluate the closure whenever you need it.
my $v = $l->();
Marking the variable lazy can be easier with prototypes:
sub delay(&){ $_[0] }
my $l = delay { 42 }
But forcing the value is pain in the neck.
This module makes it easier by making the value auto-forcing.