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.


About Brent

Associate Professor of Computer Science at Hendrix College. Functional programmer, mathematician, teacher, pianist, follower of Jesus.
This entry was posted in haskell, math. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.