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

Re: [FWP] Lazy Evaluation question (was: Anybody look at Ruby?)



"David L. Nicol" <david@kasey.umkc.edu> writes:
> 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.

It requires only a little effort to get the benefits of lazy evaluation in a
strictly-evaluated language, as long as you have the necessary mechanisms
such as closures and first-class functions.  As long as you explicitly
request evaluation whenever you want it, there isn't a problem.

> Are there really situations in which you need lazy evaluation without
> knowing about it deeply enough in advance to wrap and unwrap the closures?

Probably not.  But a friendly lazy-evaluation mechanism will ensure that the
execution of a delayed block of code is forced no more than once.  It's
probably therefore worth wrapping the closure-manipulation up in a package.
I knocked this up pretty quickly, so there may be something I've overlooked,
but you get the idea.

    package Lazy;
    use strict;

    sub delay (&) {
        my $self = [ 0, shift() ];
        return bless $self;
    }

    sub force {
        my $self = shift;

        # Do nothing if we got called on some other object
        if (ref($self) ne "Lazy") {
            return $self;
        }
        elsif ($self->[0]) {
            return $self->[1];
        }
        else {
            $self->[0] = 1;
            # Today's burning question: should Perl have an ->= operator? :-)
            $self->[1] = $self->[1]->();
            return $self->[1];
        }
    }

    1;

You can now do things like this:

    sub fif {                   # "functional if"
        my ($cond, $then, $else) = @_;
        return $cond ? $then->force() : $else->force();
    }

    fif $foo, Lazy::delay { frob() }, Lazy::delay { tweak() };

-- 
Aaron Crane   <aaron.crane@pobox.com>   <URL:http://pobox.com/~aaronc/>

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