Haskelling My Python

https://news.ycombinator.com/rss Hits: 9
Summary

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鈥檛 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鈥檚 define an infinite generator for the positive integers.Kublai: Oh, oh, I know how to do this! That鈥檚 easy!def ints(): cnt = 1 while True: yield cnt cnt += 1 Nice! That works. However, we鈥檙e 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鈥檚 actually pretty simple. The first positive integer is 1, obviously. The remaining integers after 1 are just the positive integers but with 1 added to each one. As simple as that.We鈥檒l need a function for printing out the first few elements of that generator. (Assuming you already imported the correct modules.)# take n f def take(n, f): return list(itertools.islice(f, n)) And now let鈥檚 test it with ints().>>> take(10, ints()) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Yay! It works!Next, let鈥檚 define a function to integrate a Taylor series, where the coefficients of the Taylor series will be expressed as an infinite generator. Recall that the integral of $x^n$ is $\frac{1}{n+1}x^{n+1}+C$. That means our integral is some leading constant plus all the terms of the original Taylor series shifted over by one and divided by $n+1$.# integrate f c = c : zipWith (/) f ints def integrate(f, c): yield c yield from map(operator.truediv, f, ints()) Now time for some magic. Recall that the derivative of $e^x$ is itself and $e^x = \int_0^x e^y dy + 1$ so the integration constant is 1. So, let鈥檚 use these properties to define $e^x$!# expSeries = integrate expSer...

First seen: 2025-04-21 11:35

Last seen: 2025-04-21 19:36