Zaxo has asked for the wisdom of the Perl Monks concerning the following question:
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:
lazybool.pl:#!/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;
#!/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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: A Lazy Class
by japhy (Canon) on Apr 21, 2002 at 15:00 UTC | |
by chip (Curate) on Apr 22, 2002 at 02:45 UTC | |
by japhy (Canon) on Apr 22, 2002 at 02:47 UTC | |
Re: A Lazy Class
by broquaint (Abbot) on Apr 21, 2002 at 15:27 UTC |