mastodon.scot is one of the many independent Mastodon servers you can use to participate in the fediverse.
A server intended for (but not limited to) users in Scotland or who identify as Scottish.

Server stats:

2.2K
active users

#RationalNumbers

0 posts0 participants0 posts today

Enumerating all of the (positive) #RationalNumbers in 10 lines of #Haskell code.

---------------------------------------------
data Rational = Integer :/ Integer

properFraction :: Rational -> (Integer, Rational)
properFraction (a:/ b) = if a < b then (0, (a :/ b)) else (q, (r :/ b))
where (q, r) = a `quotRem` b

calkinwilfSuccessor :: Rational -> Rational
calkinwilfSuccessor rat = b :/ (b*n + b - a) where (n, (a :/ b)) = properFraction rat

rationals :: [Rational]
rationals = iterate calkinwilfSuccessor (1 :/ 1)
---------------------------------------------

This comes from the 2004 functional pearl paper by Gibbons, Lester and Bird. The main component is a formula credited to Moshe Newman for generating the next element in the Calkin-Wilf sequence (the sequence is simply a breadth-first search enumeration of the Calkin-Wilf tree). See also: en.wikipedia.org/wiki/Calkin%E

The Gibbons, Lester, Bird paper contains many other neat pearls involving deforesting trees (Stern-Brocot and Calkin-Wilf trees), the above successor idea, and a continued fraction form which avoids arbitrary-precision integer division (at the cost of a continued fraction representation of the rationals).

Quick note: Generating all rationals using the above is easy. Change to prepend 0, then always produce (𝑥, -𝑥) one after the other with 𝑥 are all positive rationals coming from the above function.

en.wikipedia.orgCalkin–Wilf tree - Wikipedia