Last active
October 1, 2022 15:50
-
-
Save anton0xf/7d04326a72334360bf9015fd9fe918bd to your computer and use it in GitHub Desktop.
This file contains hidden or 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 itertools | |
class Cons: | |
def __init__(self, head, tail_fn): | |
self.head = head | |
self._tail_fn = tail_fn | |
self._tail = None | |
def tail(self): | |
if self._tail: | |
return self._tail | |
self._tail = self._tail_fn() | |
return self._tail | |
def __iter__(self): | |
while True: | |
yield self.head | |
self = self.tail() | |
def cons_sum(a, b): | |
return Cons(a.head + b.head, | |
lambda: cons_sum(a.tail(), b.tail())) | |
def fibs(): | |
cons = Cons(0, lambda: | |
Cons(1, lambda: | |
cons_sum(cons, cons.tail()))) | |
return cons | |
def take(n, it): | |
return list(itertools.islice(it, n)) | |
assert [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] == take(10, fibs()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment