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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.