Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python delayed execution

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

like image 654
Oleg Pavliv Avatar asked Dec 13 '22 11:12

Oleg Pavliv


1 Answers

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)

like image 139
Eric Strom Avatar answered Jan 02 '23 00:01

Eric Strom