Last active
May 4, 2019 03:44
-
-
Save 3noch/7969f416d403ba3a54a788b113c204ce to your computer and use it in GitHub Desktop.
Fixpoint for Iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try
list(fix_it(up(10)))
andfib(1000)
.