python延迟执行
要在 Lisp 中实现 流作为延迟列表,它是 推荐使用Lisp 宏。
(defmacro cons-stream (a b)
(cons ,a (delay ,b)))
(defmacro delay (expr)
`(memo-proc (lambda () ,expr)))
Python 和 Perl 会怎样做同样的事情?
编辑。是否可以
(define primes (sieve (integers-starting-from 2)))
在 Python 和 Perl 等语言中使用如此酷的构造作为流
To implement streams as delayed lists in Lisp it's recommended to use Lisp macros.
(defmacro cons-stream (a b)
(cons ,a (delay ,b)))
(defmacro delay (expr)
`(memo-proc (lambda () ,expr)))
What would by Python and Perl way to do the same thing?
EDIT. Is it possible to use such a cool construct as streams
(define primes (sieve (integers-starting-from 2)))
in languages like Python and Perl
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Python 中,最接近的结构可能是生成器表达式。
在 Perl 中,没有本地惰性列表,但该语言提供了构建惰性列表所需的所有原语。我编写了一个名为 List::Gen 的惰性列表库,可在 CPAN 上使用。
<2..>
位可以详细地写为range(2, 9**9**9)
In Python, the closest structure would probably be a generator expression.
In Perl, there is not a native lazy list, but the language provides all of the primitives that are needed to build one. I have written a lazy list library called List::Gen which is available on CPAN.
the
<2..>
bit could be written verbosely asrange(2, 9**9**9)
Perl
runrig 建议来自 Mark Dominus 出色的高阶 Perl。使用 HOP 免费提供的示例代码中的 Stream 模块,筛选Eratosthenes 是
输出:
Python
从 gist 借用代码alexbowe,Python中使用流的筛子是
输出:
其他可能性
在某些语言中,流模式是不可见的。例如,惰性求值是 Haskell 的一项功能,因此您可以将
primes
定义为Perl
runrig suggested the techniques from Mark Dominus's excellent Higher Order Perl. Using the Stream module from HOP's freely available sample code, the sieve of Eratosthenes is
Output:
Python
Borrowing code from a gist by alexbowe, the sieve in Python using streams is
Output:
Other possibilities
In some languages, the stream pattern is invisible. Lazy evaluation is a feature of Haskell, for instance, so you could define
primes
as在 Perl 中,您将使用匿名子例程(如 LISP 的 lambda)。 第 6 章 中有很多示例.perl.plover.com/" rel="nofollow">高阶 Perl
In perl you would use anonymous subroutines (like LISP's lambda). There are plenty of examples in chapter 6 of Higher Order Perl
尽管很难说出您实际想要什么,因为不同语言之间的许多事情都存在细微的差异,但您正在寻找的 Python 等价物可能是生成器,它是一种可以被要求产生下一个值然后挂起自身的函数。它们之前在(例如) 你可以使用 Python 生成器函数做什么for?,并且在其他地方有很多示例和教程 - 例如,http://www.dabeaz.com/generators/index.html
Although it's hard to tell what you actually want, since many things are subtly different between the different languages, he Python equivalent you're looking for is probably a generator, which is a kind of function that can be asked to produce the next value and then suspends itself. They were previously covered in (for example) What can you use Python generator functions for?, and there are lots of examples and tutorials of them available elsewhere -- for example, http://www.dabeaz.com/generators/index.html