问题描述
我发现Haskell和Perl6最有趣的功能之一就是能够将计算值推迟到实际需要时才使用.
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喜欢立即执行所有操作,但是据我所知,它包含所有用于惰性求值的必要原语.这些是:
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:
- 在子例程中引用
@_
会创建一个数组引用,该数组引用是其参数列表中标识符的别名,即使其中某些标识符尚不包含值. - 从内部保存
\@_
的此类子例程返回重载/绑定对象,然后在需要时取消引用. (并且有各种CPAN模块可以抽象出平局/过载细节)
- taking a reference to
@_
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. - returning overloaded / tied objects from such subroutines that hold
\@_
internally, and then dereference it when needed. (and there are various CPAN modules that abstract away the tie/overload details)
我已经在Perl中尝试了各种惰性编程技术(我的作品中有一个模块可以在Perl5中实现相当一部分的Haskell Prelude(类似于递归:$_ = list 0, 1, zipWith {&sum} $_, tail $_ for my $fibs;
这样的定义斐波那契序列的东西是已经工作)).但是我有种感觉,当在较大的表达式/程序中使用这些函数时,代码中会隐藏一些细微的错误.
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.
所以我想知道是否有任何好的例子(CPAN/博客/书籍),有人知道使用Haskell/Perl6像Perl5中的懒惰吗?特别是,我想通读使用这种惰性的任何规模很大的代码.
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.
我也想知道是否有人在Perl 5中实施延迟评估时遇到任何麻烦或棘手的问题.
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.
推荐答案
高级Perl(免费提供在线 )的一章称为无限流".也许这是一个很好的起点.
Higher-Order Perl (freely available online) has a chapter called "Infinite Streams". Maybe that's a good starting point.
这篇关于Perl 5中的惰性评估技术示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!