Skip to content

Instantly share code, notes, and snippets.

Created September 2, 2015 10:15
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Python is super-readable and concise!
merge xxs@(x:xs) yys@(y:ys) =
case compare x y of
LT -> x : merge xs yys
EQ -> x : merge xs ys
GT -> y : merge xxs ys
xs = map (*2) hamming
ys = map (*3) hamming
zs = map (*5) hamming
hamming = 1 : xs `merge` ys `merge` zs
main = print $ take 100 hamming
class lazy(object):
def __init__(self, f):
self.b = True
self.x = f
def force(self):
if self.b:
self.b = False
self.x = self.x()
return self.x
def merge(xxs, yys):
def go():
x, xs = xxs.force()
y, ys = yys.force()
if x < y:
return (x, merge(xs, yys))
elif x == y:
return (x, merge(xs, ys))
return (y, merge(xxs, ys))
return lazy(go)
def fmap(f, xxs):
def go():
x, xs = xxs.force()
return (f(x), fmap(f, xs))
return lazy(go)
def hamming():
def go():
ps = merge(xs, ys)
qs = merge(ps, zs)
return (1, qs)
go = lazy(go)
xs = fmap(lambda x: x * 2, go)
ys = fmap(lambda y: y * 3, go)
zs = fmap(lambda z: z * 5, go)
return go
hamming = hamming()
def take(n, xs):
def go(xs = xs):
for _ in range(n):
x, xs = xs.force()
yield x
return list(go())
print(take(100, hamming))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment