Rationals!
Posted on August 13, 2007
Tagged rational
Tagged rational
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
:x2:xs) = (x1 + x2) : x1 : buildHB (x2:xs)
buildHB (x1= 1 : 1 : buildHB hypbin
hypbin = zipWith (%) hypbin (tail hypbin) rationals
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.