Please, consider this Python 3 code to generate prime numbers using an unbounded sieve of eratosthenes:
import itertools
def primes():
numbers = itertools.count(2)
while True:
prime = next(numbers)
yield prime
numbers = filter(prime.__rmod__,numbers)
prime_gen = primes()
next(prime_gen)
# Prints 2
next(prime_gen)
# Prints 3
next(prime_gen)
# Prints 5
next(prime_gen)
# Prints 7
So far so good. Now, let's replace the prime.__rmod__
function with a lambda that does the same thing:
import itertools
def primes():
numbers = itertools.count(2)
while True:
prime = next(numbers)
yield prime
numbers = filter(lambda n: n % prime,numbers)
prime_gen = primes()
next(prime_gen)
# Prints 2
next(prime_gen)
# Prints 3
next(prime_gen)
# Prints 4
next(prime_gen)
# Prints 5
Why the lambda function is not working with the filter? There is something going on with the scope of the lambda function?