Haskelling My Python
Published on: 2025-08-16 03:45:56
Haskelling My Python Reimplementing Haskell lazy infinite lists using Python generators
A few years ago, Pleng showed me a really cool trick you can do with lazy infinite lists in Haskell.
Kublai: Oh no, not Haskell! 😱
Don’t worry. There will be no mandatory Haskell in this post (although it is a really nice language which you should check out!). Instead, today Erik asked me if that trick also works using infinite Python generators, and turns out it does!
First, as a warm-up, let’s define an infinite generator for the positive integers.
Kublai: Oh, oh, I know how to do this! That’s easy!
def ints (): cnt = 1 while True : yield cnt cnt += 1
Nice! That works. However, we’re going to define it in a slightly different way. Recursively! The commented line is Haskell and below that is the translation into Python.
# ints = 1 : map (+1) ints def ints (): yield 1 yield from map( lambda x: x + 1 , ints())
Kublai: WTF? How does that work?
It’s actually pretty simple. The first positive
... Read full article.