python延迟执行

发布于 2024-11-17 15:50:18 字数 527 浏览 0 评论 0原文

要在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

神也荒唐 2024-11-24 15:50:18

在 Python 中,最接近的结构可能是生成器表达式。

在 Perl 中,没有本地惰性列表,但该语言提供了构建惰性列表所需的所有原语。我编写了一个名为 List::Gen 的惰性列表库,可在 CPAN 上使用。

use List::Gen '*';

my $primes = <2..>->filter(\&is_prime);  # where you provide &is_prime

say "@$primes[0..10]";  # lazily finds the first 11 primes

<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.

use List::Gen '*';

my $primes = <2..>->filter(\&is_prime);  # where you provide &is_prime

say "@$primes[0..10]";  # lazily finds the first 11 primes

the <2..> bit could be written verbosely as range(2, 9**9**9)

呆橘 2024-11-24 15:50:18

Perl

runrig 建议来自 Mark Dominus 出色的高阶 Perl。使用 HOP 免费提供的示例代码中的 Stream 模块,筛选Eratosthenes 是

#! /usr/bin/env perl

use strict;
use warnings;

use Stream qw/ filter head node promise show tail upfrom /;

use subs 'sieve';  # no parens on recursive calls
sub sieve {
  my($s) = @_;
  my $n = head $s;
  node $n, promise { sieve filter { $_[0] % $n != 0 } tail $s };
}

sub primes { sieve upfrom 2 }

show primes, 10;

输出:

$ ./primes
2 3 5 7 11 13 17 19 23 29

Python

gist 借用代码alexbowe,Python中使用流的筛子是

#! /usr/bin/env python

null_stream = (None, None)

def reduce(f, result, stream):
    if stream is null_stream: return result
    return reduce(f, f(result, head(stream)), tail(stream))

def take(N, stream):
    if N <= 0 or stream is null_stream: return null_stream
    return (head(stream), lambda: take(N-1, tail(stream)))

def filter(pred, stream):
    if stream is null_stream: return null_stream
    if pred(head(stream)):
        return (head(stream), lambda: filter(pred, tail(stream)))
    return filter(pred, tail(stream))

def integers_from(N): return (N, lambda: integers_from(N+1))
def head((H, _)): return H
def tail((_, T)): return T()
def to_array(stream): return reduce(lambda a, x: a + [x], [], stream)

def sieve(stream):
    if stream is null_stream: return null_stream
    h = head(stream)
    return (h, lambda: sieve(filter(lambda x: x%h != 0, tail(stream))))

def primes(): return sieve(integers_from(2))

print to_array(take(10, primes()))

输出:

$ ./prymes 
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

其他可能性

在某些语言中,流模式是不可见的。例如,惰性求值是 Haskell 的一项功能,因此您可以将 primes 定义为

primes = sieve [2 ..]
  where sieve (x:xs) =
          let remains = filter (not . isMultipleOf x) xs
          in x : sieve remains
        isMultipleOf a b = b `mod` a == 0

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

#! /usr/bin/env perl

use strict;
use warnings;

use Stream qw/ filter head node promise show tail upfrom /;

use subs 'sieve';  # no parens on recursive calls
sub sieve {
  my($s) = @_;
  my $n = head $s;
  node $n, promise { sieve filter { $_[0] % $n != 0 } tail $s };
}

sub primes { sieve upfrom 2 }

show primes, 10;

Output:

$ ./primes
2 3 5 7 11 13 17 19 23 29

Python

Borrowing code from a gist by alexbowe, the sieve in Python using streams is

#! /usr/bin/env python

null_stream = (None, None)

def reduce(f, result, stream):
    if stream is null_stream: return result
    return reduce(f, f(result, head(stream)), tail(stream))

def take(N, stream):
    if N <= 0 or stream is null_stream: return null_stream
    return (head(stream), lambda: take(N-1, tail(stream)))

def filter(pred, stream):
    if stream is null_stream: return null_stream
    if pred(head(stream)):
        return (head(stream), lambda: filter(pred, tail(stream)))
    return filter(pred, tail(stream))

def integers_from(N): return (N, lambda: integers_from(N+1))
def head((H, _)): return H
def tail((_, T)): return T()
def to_array(stream): return reduce(lambda a, x: a + [x], [], stream)

def sieve(stream):
    if stream is null_stream: return null_stream
    h = head(stream)
    return (h, lambda: sieve(filter(lambda x: x%h != 0, tail(stream))))

def primes(): return sieve(integers_from(2))

print to_array(take(10, primes()))

Output:

$ ./prymes 
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

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

primes = sieve [2 ..]
  where sieve (x:xs) =
          let remains = filter (not . isMultipleOf x) xs
          in x : sieve remains
        isMultipleOf a b = b `mod` a == 0
谁的年少不轻狂 2024-11-24 15:50:18

在 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

内心激荡 2024-11-24 15:50:18

尽管很难说出您实际想要什么,因为不同语言之间的许多事情都存在细微的差异,但您正在寻找的 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文