I've been looking for an example of co-(Elgot algebra)s for quite some time, and I came across a surprisingly nice example while working on my gmpint package.

The problem is simple: we wish to convert a number to its base \( b \) representation. This turns out to be useful since GMP uses arrays of limbs0 to represent large integers; we need conversions to base \( 2 ^{64} \).

This can be accomplished with a co-(Elgot algebra) as follows:

import Data.Functor.Foldable import Data.Word

integerToWordList :: Integer -> [Word64] integerToWordList = coelgot pa c where c i = Cons (fromIntegral (i `mod` (2 ^ (64 :: Int)))) (i `div` (2 ^ (64 :: Int))) pa (i, ws) | i < 2 ^ (64 :: Int) = [fromIntegral i] | otherwise = embed ws

This does not entirely justify the added complexity relative to using an apomorphism (or even writing the recursion by hand), but I think this example is nonetheless instructive.

You can see this co-(Elgot algebra) in the wild here. It is in fact the only example of a co-(Elgot algebra) on the entirety of Hackage!

0: For our purposes, the limbs can be thought of as Word64s.