[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] general Lazy Evaluation implemented with tie




John Porter wrote:
> 
> David L. Nicol wrote:
> >
> > perl -e '$clo = sub {2 + ++$tally}; $r = \$clo ; print &$$r, &$$r'
> >
> > i wonder how much trouble a LAZY type would be to create, which
> > would appear to the rest of the syntax as a scalar, but only get
> > evaluated when it is evaluated.
> 
> This is what tie is for, no?
> 
>   {
>     package Scalar::Closure;
>     sub TIESCALAR { bless $_[1], $_[0] }
>     sub FETCH { $_[0]->() }
>   }
> 
>   tie $x, 'Scalar::Closure', sub { $n++ };
>   
>
> works.
> 
> --
> John Porter

If you extend it a little more, it breaks down...


sub threeprint($){print $_[0],$_[0],$_[0],"\n"};

sub sixprint($){my $x=shift; print $x, $x, $x, "\n"};

threeprint($x);
sixprint($x);

To force the evaluation  within the accesses in sixprint,
AFTER the evaluation , is why a Whole New Type would be
required.

If you use pass-by-reference all the time you could have
as finely grained control as you wish; and in functional language
contexts where full memoization is going to happen (instead of
the contrived side effect we've been using here) getting the
value out of it the first time is absolutely okay.

Maybe we need automatic resolution of references -- do we have that?

easy enough to build if or when needed:

sub recursivescalardereference(@){
	# careful -- will get stuck in reference loops
	map {ref $_ ?  recursivescalardereference($$_) : $_} @_
};

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe