Rationals!

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 these ads
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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s