I have use for a boolean class which is lazy evaluated. That is, it will take no value until needed, after which its value is memoized.
I want this for testing complicated nests of logical operators, but a similar construction would be useful for expensive functions.
I've implemented this in terms of a closure in the constructor and overload 'bool'. I'm not very satisfied with the implementation. The $foo->{peek}{} notation for the closures is really ugly, but I like the way overloading works here. I'd appreciate any suggestions for a cleaner interface. Is there an idiom for this? Would tie help?
Here's the module and a demo script: #!/usr/bin/perl -w
use strict;
package LazyBool;
use constant THE_BIT => 1 << 9;
use constant RAND_SIZE => 1 << 16;
use overload 'bool' => sub {
my $self = shift;
$self->{value}();
};
sub new {
my $class = shift;
my ($value,$self) = (undef,{});
$self->{value} = sub {
defined $value ?
$value :
$value = THE_BIT & rand(RAND_SIZE) ? 1 : 0;
};
$self->{peek} = sub {
$value;
};
bless $self, $class;
}
1;
lazybool.pl: #!/usr/bin/perl -w
use strict;
use LazyBool;
my $foo = LazyBool->new;
print '$foo is ',
defined $foo->{peek}() ? $foo->{peek}() : "not defined",
'.',
$/;
print $foo,$/;
print '$foo is ',
defined $foo->{peek}()? $foo->{peek}() : "not defined",
'.',
$/;
=pod
$ perl lazybool.pl
$foo is not defined.
0
$foo is 0.
$ perl lazybool.pl
$foo is not defined.
0
$foo is 0.
$ perl lazybool.pl
$foo is not defined.
1
$foo is 1.
=cut
After Compline, Zaxo
In reply to A Lazy Class
by Zaxo
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|