Infinite lists and generators
tjreedy at home.com
Wed Nov 14 17:32:28 CET 2001
"Luigi Ballabio" <ballabio at mac.com> wrote in message
news:mailman.1005728119.32612.python-list at python.org...
> Hi all,
> I've been reading a few back issues of the Perl Journal, and I came
> an article on implementing infinite lists in Perl. Just for fun I
> ahead and reimplemented it in Python---I know someone probably did
> but as I said, it was for fun. Also, I've written a test suite which
> showcases a few tricks such as building the list of all prime
> the Hamming numbers, and the power series of exp, sin and cos. I'm
> including the file below.
> My question is: how does one go about pulling such stunts with
Two easy examples (untested, but pretty sure correct):
"Infinite stream of integers starting from n"
> return Stream(n,lambda n=n:integersFrom(n+1))
n += 1
> """returns the stream of the elements x of the
> input stream s which satisfy the predicate f"""
> while s and not f(s.head()):
> s = s.tail()
> if not s:
> return None
> return Stream(s.head(),
> lambda f=f,s=s: filter(f,s.tail()))
The problem with filtering an infinite stream is that if there are
only N items that pass, the filter will never halt looking for the
"returns the stream of x, f(x), f(f(x)), f(f(f(x))), ..."
> return Stream(x,
> lambda f=f,x=x: iterate(f,f(x)))
x = f(x)
Terry J. Reedy
More information about the Python-list