« Deducing code from types: filterM » Mapping over a nested functor?

Rationals!

Posted on August 13, 2007
Tagged
Inspired by this totally sweet paper by Calkin & Wilf (read it for more details, it’s very short and quite elegantly written) (no really, you should read it):
import Data.Ratio

buildHB (x1:x2:xs) = (x1 + x2) : x1 : buildHB (x2:xs)
hypbin = 1 : 1 : buildHB hypbin
rationals = zipWith (%) hypbin (tail hypbin)

How cool is that? The infinite list of all positive rational numbers, each occurring exactly once in reduced form. In only three lines of Haskell. There are actually better ways to do this; e.g. see the functional pearl by Gibbons, Lester, and Bird. In particular the three-line version above uses O(n) memory to generate the first n rationals, since half of the hypbin list has to be kept around to generate the rest of it, whereas it can actually be done in constant memory. But it’s still nifty.