functional python: a simple infinite list example

The object oriented, “duck typed” programming language python has also some functional features on par with serious functional languages.

One example for these advanced functional elements are the infinite lists (as generators and iterators):

# sieve of Erastothenes
from itertools import count
from itertools import ifilter
def sieve(possible_primes):
  next_prime=possible_primes.next()
  yield next_prime
  for i in sieve(ifilter(lambda j: j%next_prime!=0, possible_primes)):
    yield i

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


Leave a Reply

(required)

There aren't any comments at the moment, be the first to start the discussion!