NAME
FP::Lazy - lazy evaluation (delayed evaluation, promises)
SYNOPSIS
use FP::Lazy;
my $a = lazy { 1 / 0 };
eval {
print force $a
};
like $@, qr/^Illegal division by zero/;
eval {
$a + 2
};
like $@, qr/^non-auto-forcing promise accessed via 0\+ operation/;
my $count = 0;
my $b = lazy { $count++; 1 / 2 };
is is_promise($b), 1;
is $count, 0;
is force($b), 1/2; # increments $count
is $count, 1;
# $b is still a promise at this point (although an evaluated one):
is is_promise($b), 1;
is force($b), 1/2; # does not increment $count anymore
is $count, 1;
# The following stores result of `force $b` back into $b
FORCE $b;
is is_promise($b), undef;
is $b, 1/2;
is $count, 1;
# Note that lazy evaluation and mutation usually doesn't mix well -
# lazy programs better be purely functional. Here $tot depends not
# just on the inputs, but also on how many elements were evaluated:
use FP::Stream qw(stream_map); # uses `lazy` internally
use FP::List;
{
my $tot = 0;
my $l = stream_map sub {
my ($x) = @_;
$tot += $x;
$x*$x
}, list (5,7,8);
is $tot, 0;
is $l->first, 25;
is $tot, 5;
is $l->length, 3;
is $tot, 20;
}
# Also note that `local` does mutation (even if in a somewhat
# controlled way):
our $foo = "";
sub moo {
my ($bar) = @_;
local $foo = "Hello";
lazy { "$foo $bar" }
}
is moo("you")->force, " you";
# runtime conditional lazyness:
sub condprom {
my ($cond) = @_;
lazy_if { 1 / 0 } $cond
}
ok is_promise(condprom 1);
eval {
# immediate division by zero exception (still pays
# the overhead of two subroutine calls, though)
condprom 0
};
like $@, qr/^Illegal division by zero/;
# Calling methods on those promises will automatically force them,
# which is normally necessary since there's no way to know the
# class of the object otherwise:
use FP::Lazy qw(is_forced);
{
my $l = lazy { cons(1, null) };
ok !is_forced($l);
my $l2 = $l->cons(10);
# $l was forced even though the only reason is to know which
# class to call `cons` on:
ok is_forced($l);
}
# There's `lazyT` which specifies the (or a base) class of the
# object statically, hence there's no need to evaluate a promise
# just to call a method. In this case the called method receives
# the unevaluated promise as its argument! (This might change in
# that either some flag in the the interface definition, or simply
# the stream_ prefix of a method could be required, otherwise it
# would still be forced. That would make it safe(r) but *maybe*
# (given a good test suite) it's not necessary?)
{
my $l = lazyT { cons(1, null) } "FP::List::Pair";
ok !is_forced($l);
my $l2 = $l->cons(10);
# $l has *not* been forced now.
ok !is_forced($l);
}
# And `lazyT_if` which is the conditional variant:
sub typed_condprom {
my ($cond) = @_;
lazyT_if { list(1 / 0) } "FP::List::List", $cond
}
ok is_promise(typed_condprom 1);
eval {
# immediate division by zero exception (still pays
# the overhead of two subroutine calls, though)
typed_condprom 0
};
like $@, qr/^Illegal division by zero/;
# A `lazyLight` promise is re-evaluated on every access:
my $z = 0;
my $v = lazyLight { $z++; 3*4 };
is force($v), 12;
is $z, 1;
is force($v), 12;
is $z, 2;
# There are 3 possible motivations for lazyLight: (1) lower
# allocation cost (save the wrapper data structure); (2) no risk
# for circular references (due to storing the result back into the
# wrapper (mutation) that can be used recursively); (3) to get
# fresh re-evaluation on every access and thus picking up any
# potential side effect.
# Arguably (3) is against the functional programming idea, and is
# a bit of a mis-use of lazyLight. For now, FP::TransparentLazy
# still helps this case by not using `FORCE` automatically. (TODO:
# provide another type that provides this with a guarantee?)
# Note that manual use of `FORCE` still stops the re-evalution:
ok ref $v;
is FORCE($v), 12;
is $z, 3;
is force($v), 12;
is $z, 3; # you can see that re-evaluation has stopped
ok not ref $v;
DESCRIPTION
This implements promises, a data type that represents an unevaluated or evaluated computation. The computation represented by a promise is only ever evaluated once, after which point its result is saved in the promise, and subsequent requests for evaluation are simply returning the saved value.
my $p = lazy { "......" }; # returns a promise that represents the computation
# given in the block of code
force $p; # runs the block of code and stores the result within the
# promise and also returns it
FORCE $p; # or FORCE $p,$q,$r;
# in addition to running force, stores back the resulting
# value into the variable given as argument ($p, $q, and $r
# respectively (the commented example forces 3 (possibly)
# separate values))
is is_promise($p), undef; # returns true iff $x holds a promise
NOTE
The thunk (code body) of a promise is always evaluated in scalar context, even if it is being forced in list or void context.
NAMING
The name `lazy` for the delaying form was chosen because it seems what most frameworks for functional programming on non-functional programming languages are using, as well as Ocaml. We don't want to stand in the way of what people expect, after all.
Scheme calls the lazy evaluation form `delay`. This seems to make sense, as that's a verb, unlike `lazy`. There's a conceptually different way to introduce lazyness, which is to change the language to be lazy by default, and `lazy` could be misunderstood to be a form that changes the language in its scope to be that. Both for this current (slight?) risk for misinterpretation, and to reserve it for possible future implementation of this latter feature, it seems to be wise to use `delay` and not `lazy` for what this module offers.
What should we do?
(To experiment with the style, or in case you're stubborn, you can explicitely import `delay` or import the `:all` export tag to get it.)
TODO
If the thunk of a promise throws an exception, the promise will remain unevaluated. This is the easiest (and most efficient) thing to do, but there remains a question about the safety: if the data source is read-once (like reading lines from files), and the exception happens after the read, then forcing the promise again will fetch and store the next line, hence a line will be lost. Since exceptions can happen because of out of memory conditions or from signal handlers, this will be of real concern in some situations.
Provide safe promises for these situations? (But that would mean that they need to be implemented in C as Perl does not offer the features to implement them safely, correct?)
DEBUGGING
Lazy code can be difficult to debug because the context in which the code that evaluates a promise runs is not the same context in which the promise was captured. There are two approaches to make this easier:
$ENV{DEBUG_FP_LAZY} = "1"
or local $FP::Lazy::debug=1
-- captures a backtrace in every promise (slow, of course!). Use the optionally exported lazy_backtrace
function to get the backtrace (or look at it via the repl's :d (Data::Dumper) mode).
$ENV{DEBUG_FP_LAZY} = "eager"
or local $FP::Lazy::eager=1
-- completely turns of any lazyness (except for lazyLight, currently); easy stack traces and flow logic but of course the program behaves differently; beware of infinite lists!
SEE ALSO
https://en.wikipedia.org/wiki/Futures_and_promises
Alternative Data::Thunk, but see note in TODO file about problems.
Alternative Scalar::Defer?
FP::Mixin::Utils -- Lazy implements this as a fallback (lower priority than forcing the promise and finding the method on the result)
NOTE
This is alpha software! Read the status section in the package README or on the website.