I find that one of the most interesting features of both Haskell and Perl6 is the ability to defer calculating values until they are actually needed.
Perl5 on the other hand likes to do everything immediately, but from what I can tell, contains all of the necessary primitives for lazy evaluation. Those are:
@_
in a subroutine creates an array reference that is aliased to the identifiers in its argument list, even if some of those identifiers do not contain values yet.\@_
internally, and then dereference it when needed. (and there are various CPAN modules that abstract away the tie/overload details)I've been experimenting with various lazy programming techniques in Perl (I have a module in the works that implements a fair bit of the Haskell Prelude in Perl5 (things like co-recursion: $_ = list 0, 1, zipWith {&sum} $_, tail $_ for my $fibs;
to define the Fibonacci sequence are already working)). But I have a feeling that there are some subtle bugs hiding in the code that may manifest when the functions are used in larger expressions / programs.
So I am wondering if there are any good examples (CPAN / blogs / books) that anyone knows of that employ Haskell/Perl6 like laziness in Perl5? In particular, I would like to read through any code of significant size that employs this type of laziness.
I would also be interested to know if anyone has run into any gotchas or intractable problems surrounding the implementation of lazy evaluation in Perl 5.
Lazy evaluation is an evaluation strategy which holds the evaluation of an expression until its value is needed. It avoids repeated evaluation. Haskell is a good example of such a functional programming language whose fundamentals are based on Lazy Evaluation.
Raku uses lazy evaluation of lists, so one can assign infinite lists to variables and use them as arguments to functions, but unlike Haskell and Miranda, Raku does not use lazy evaluation of arithmetic operators and functions by default.
To implement lazy evaluation in our interpreter we need to modify the applica- tion expression evaluation rule to delay evaluating the operand expressions until they are needed. To do this, we introduce a new datatype known as a thunk. We define a Python class, Thunk for representing thunks.
Languages that support lazy evaluation are usually functional programming languages like Haskell, which is lazy by default. Some languages, like OCaml and Scheme, let you opt into lazy behavior. Other languages like Swift and Perl 6 support it only for lists.
Higher-Order Perl (freely available online) has a chapter called "Infinite Streams". Maybe that's a good starting point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With