Skip to content

Instantly share code, notes, and snippets.

@anton0xf
Last active October 1, 2022 15:50
Show Gist options
  • Save anton0xf/7d04326a72334360bf9015fd9fe918bd to your computer and use it in GitHub Desktop.
Save anton0xf/7d04326a72334360bf9015fd9fe918bd to your computer and use it in GitHub Desktop.
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