The following defines the infinite list of primes as a generator [chap 6.5 of the library]
def sieve(l): p = l.next() yield p for x in sieve(l): if x % p != 0: yield x After that from itertools import * >>> [p for i,p in izip(range(10), sieve(count(2)))] [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] >>> I tried to write a shorter generator expression based sieve but cant get it right. Can someone help? Heres the non-working code def si(l): p = l.next() yield p (x for x in si(l) if x % p != 0) There should be an yield or return somewhere but cant figure it out On 9/18/07, Lorenzo Stella <[EMAIL PROTECTED]> wrote: > Hi all, > I haven't experienced functional programming very much, but now I'm > trying to learn Haskell and I've learned that: 1) in functional > programming LISTS are fundmental; 2) any "cycle" in FP become > recursion. > I also know that Python got some useful tool such as map, filter, > reduce... so I told: "let's try some FP-style programming with > Python!". I took a little example of Haskell: > > listprimes :: Integer -> [Integer] > listprimes n = if n == 0 then sieve [2..] else sieve [2..(n-1)] > where > sieve [] = [] > sieve (p:xs) = p : sieve (filter (\x -> mod x p > 0) xs) > > and I tried to "translate" it in Python: > > def sieve(s): > if s == []: > return [] > else: > return [s[0]] + sieve(filter((lambda x: x % s[0] > 0), > s[1:])) > > def listprimes(n): > return sieve(range(2,n)) > > These should be almost the same: listprimes actually lists prime > integers up to n-1. The result is: Haskell implementation works well, > maybe it's not the better way to do it, but it does what I wanted. > Python implementation gives me > > RuntimeError: maximum recursion depth exceeded in cmp > > My question is: how can we call a language "functional" if it's major > implementation has a limited stack? Or is my code wrong? > > LS > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list