Skip to content

Instantly share code, notes, and snippets.

@3noch
Last active May 4, 2019 03:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3noch/7969f416d403ba3a54a788b113c204ce to your computer and use it in GitHub Desktop.
Save 3noch/7969f416d403ba3a54a788b113c204ce to your computer and use it in GitHub Desktop.
Fixpoint for Iterators
import collections.abc as ABC
from itertools import islice, tee
class MutableIterator(ABC.Iterator):
def __init__(self, nexts=()):
self.nexts = list(nexts)
def __next__(self):
if self.nexts:
return self.nexts.pop()
else:
raise StopIteration()
def append(self, new):
self.nexts += [new]
def fix_it(it):
"""Fixpoint for iterators."""
self = MutableIterator()
for i in it(self):
self.append(i)
yield i
# Example
def recursive_fibs(self):
yield from (0, 1, 1)
(left, right) = tee(self)
next(right)
yield from (x + y for (x, y) in zip(left, right))
def fib(n):
return next(islice(fix_it(recursive_fibs), n-1, None))
# Another example
def up(n):
def k(self):
yield 0
yield from (x + 1 for x in self if x < n - 1)
return k
@3noch
Copy link
Author

3noch commented Apr 25, 2019

Try list(fix_it(up(10))) and fib(1000).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment