编程语言
首页 > 编程语言> > python延迟执行

python延迟执行

作者:互联网

要在Lisp中实现streams as delayed lists,使用Lisp宏是recommended.

(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等语言中

解决方法:

Perl的

runrig suggested Mark Dominus出色的Higher Order Perl技术.使用HOP免费提供的样品代码Stream module,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 by 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 = sieve [2 ..]
  where sieve (x:xs) =
          let remains = filter (not . isMultipleOf x) xs
          in x : sieve remains
        isMultipleOf a b = b `mod` a == 0

标签:python,perl,lisp,sicp
来源: https://codeday.me/bug/20190715/1462615.html